JQuery中$.each 和$(selector).each()的区别详解
一个通用的遍历函数,可以用来遍历对象和数组.数组和含有一个length属性的伪数组对象(伪数组对象如function的arguments对象)以数字索引进行遍历,从0到length-1,其它的对象通过的属性进行遍历.
$.each()与$(selector).each()不同,后者专用于jquery对象的遍历,前者可用于遍历任何的集合(无论是数组或对象),如果是数组,回调函数每次传入数组的索引和对应的值(值亦可以通过this关键字获取,但javascript总会包装this值作为一个对象—尽管是一个字符串或是一个数字),方法会返回被遍历对象的第一参数。
例子:———传入数组
<!DOCTYPEhtml>
<html>
<head>
<scriptsrc=”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
例子:———如果一个映射作为集合使用,回调函数每次传入一个键-值对
<!DOCTYPEhtml>
<html>
<head>
<scriptsrc=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<script>
varmap={
‘flammable':‘inflammable',
‘duh':‘noduh'
};
$.each(map,function(key,value){
alert(key+‘:‘+value);
});
</script>
</body>
</html>
//输出
flammable:inflammable
duh:noduh
例子:———回调函数中returnfalse时可以退出$.each(),如果返回一个非false即会像在for循环中使用continue一样,会立即进入下一个遍历
<!DOCTYPEhtml>
<html>
<head>
<style>
div{color:blue;}
div#five{color:red;}
</style>
<scriptsrc=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<divid=”one”></div>
<divid=”two”></div>
<divid=”three”></div>
<divid=”four”></div>
<divid=”five”></div>
<script>
vararr=["one","two","three","four","five"];//数组
varobj={one:1,two:2,three:3,four:4,five:5};//对象
jQuery.each(arr,function(){ //this指定值
$(“#”+this).text(“Mineis”+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>
//输出
Mineisone.–1
Mineistwo.–2
Mineisthree.–3
-4
-5
例子:———遍历数组的项,传入index和value
<!DOCTYPEhtml>
<html>
<head>
<scriptsrc=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<script>
$.each(['a','b','c'],function(i,l){
alert(“Index#”+i+“:”+l);
});
</script>
</body>
</html>
例子:———遍历对象的属性,传入key和value
<!DOCTYPEhtml>
<html>
<head>
<scriptsrc=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<script>
$.each({name:“John”,lang:“JS”},function(k,v){
alert(“Key:”+k+“,Value:”+v);
});
</script>
</body>
</html>
正自评论的例子
1.如果不想输出第一项(使用retruntrue)进入下一遍历
<!DOCTYPEhtml>
<html>
<head>
<scriptsrc=”http://code.jquery.com/jquery-latest.js”></script>
</head>
<body>
<script>
varmyArray=["skipThis","dothis","andThis"];
$.each(myArray,function(index,value){
if(index==0){
returntrue;//equivalentto‘continue'withanormalforloop
}
//elsedostuff…
alert(index+“:“+value);
});
</script>
</body>
</html>