$.each()

$.each()与$(selector).each()不同, 后者专用于jquery对象的遍历, 前者可用于遍历任何的集合(无论是数组或对象),如果是数组,回调函数每次传入数组的索引和对应的值(值亦可以通过this 关键字获取,但javascript总会包装this 值作为一个对象—尽管是一个字符串或是一个数字),方法会返回被遍历对象的第一参数.
---------------------------------------------------
//例子:———传入数组

<!DOCTYPE html>
<html>
<head>
<script src=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<script>

$.each([52, 97], function(index, value) {
alert(index + ‘: ‘ + value);
});

</script>
</body>
</html>

//输出

0: 52
1: 97

---------------------------------------------------
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//例子:———如果一个映射作为集合使用,回调函数每次传入一个键-值对

<!DOCTYPE html>
<html>
<head>
<script src=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<script>

var map = {
‘flammable’: ‘inflammable’,
‘duh’: ‘no duh’
};
$.each(map, function(key, value) {
alert(key + ‘: ‘ + value);
});

</script>
</body>
</html>

//输出

flammable: inflammable
duh: no duh

---------------------------------------------------
//例子:———回调函数中 return false时可以退出$.each(), 如果返回一个非false 即会像在for循环中使用continue 一样, 会立即进入下一个遍历

<!DOCTYPE html>

<html>

<head>

<style>

div { color:blue; }

div#five { color:red; }

</style>

<script src=”http://code.jquery.com/jquery-latest.js”></script>

</head>

<body>

<div id=”one”></div>

<div id=”two”></div>

<div id=”three”></div>

<div id=”four”></div>

<div id=”five”></div>

<script>

var arr = [ "one", "two", "three", "four", "five" ];//数组

var obj = { one:1, two:2, three:3, four:4, five:5 }; // 对象

jQuery.each(arr, function() { // this 指定值

$(“#” + this).text(“Mine is ” + this + “.”); // this指向为数组的值, 如one, two

return (this != “three”); // 如果this = three 则退出遍历

});

jQuery.each(obj, function(i, val) { // i 指向键, val指定值

$(“#” + i).append(document.createTextNode(” – ” + val));

});

</script>

</body>

</html>

// 输出

Mine is one. – 1
Mine is two. – 2
Mine is three. – 3
- 4
- 5
---------------------------------------------------
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值