一個(gè)通用的遍歷函數(shù) , 可以用來(lái)遍歷對(duì)象和數(shù)組. 數(shù)組和含有一個(gè)length屬性的偽數(shù)組對(duì)象 (偽數(shù)組對(duì)象如function的arguments對(duì)象)以數(shù)字索引進(jìn)行遍歷,從0到length-1, 其它的對(duì)象通過(guò)的屬性進(jìn)行遍歷.
$.each()與$(selector).each()不同, 后者專用于jquery對(duì)象的遍歷, 前者可用于遍歷任何的集合(無(wú)論是數(shù)組或?qū)ο?,如果是數(shù)組,回調(diào)函數(shù)每次傳入數(shù)組的索引和對(duì)應(yīng)的值(值亦可以通過(guò)this 關(guān)鍵字獲取,但javascript總會(huì)包裝this 值作為一個(gè)對(duì)象―盡管是一個(gè)字符串或是一個(gè)數(shù)字),方法會(huì)返回被遍歷對(duì)象的第一參數(shù)。
例子:―――傳入數(shù)組
<!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
例子:―――如果一個(gè)映射作為集合使用,回調(diào)函數(shù)每次傳入一個(gè)鍵-值對(duì)
<!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
例子:―――回調(diào)函數(shù)中 return false時(shí)可以退出$.each(), 如果返回一個(gè)非false 即會(huì)像在for循環(huán)中使用continue 一樣, 會(huì)立即進(jìn)入下一個(gè)遍歷
<!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" ];//數(shù)組
var obj = { one:1, two:2, three:3, four:4, five:5 }; // 對(duì)象
jQuery.each(arr, function() { // this 指定值
$(“#” + this).text(“Mine is ” + this + “.”); // this指向?yàn)閿?shù)組的值, 如one, two
return (this != “three”); // 如果this = three 則退出遍歷
});
jQuery.each(obj, function(i, val) { // i 指向鍵, val指定值
$(“#” + i).append(document.createTextNode(”
主站蜘蛛池模板:
封丘县|
宝山区|
松桃|
鄂托克前旗|
新余市|
苍山县|
纳雍县|
宣城市|
新源县|
阿拉善右旗|
苏尼特右旗|
滨州市|
庆元县|
玉龙|
佛学|
呼图壁县|
延津县|
多伦县|
左贡县|
台州市|
岫岩|
汤阴县|
延安市|
金乡县|
临安市|
奈曼旗|
兴业县|
天等县|
镇康县|
永宁县|
乌拉特后旗|
永兴县|
巴南区|
潮州市|
瑞昌市|
新兴县|
额济纳旗|
揭阳市|
巴中市|
香格里拉县|
同江市|