1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script> 6 <script type="text/javascript"> 7 $(function(){ 8 $.each([1,2,3],function(index,value){ 9 alert(index+"=="+value); 10 }) 11 }) 12 </script> 13 </head> 14 15 <body> 16 17 </body> 18 </html>
jquery each()函数用于遍历指定的对象和数组。
语法
$.each(object,callback)
遍历对象
1 <script type="text/javascript"> 2 $(function(){ 3 var obj = { 4 "site":"你我他学习吧", 5 "author":"张学亮" 6 } 7 $.each(obj,function(key,value){ 8 alert(key + "==" + value); 9 }) 10 }) 11 </script>
遍历数组
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script> 6 <script type="text/javascript"> 7 $(function(){ 8 var arr = ["one","two","three","four","five"]; 9 var obj = {one:1,two:2,three:3,four:4,five:5}; 10 $.each(arr,function(i,val){ 11 $("#"+val).text("我的是 "+val+"."); 12 //在three之后停止运行 13 //return (val !== "three"); 14 }); 15 $.each(obj,function(i,val){ 16 $("#"+i).append(document.createTextNode(" - "+val)); 17 }) 18 }) 19 </script> 20 </head> 21 22 <body> 23 <div id="one"></div> 24 <div id="two"></div> 25 <div id="three"></div> 26 <div id="four"></div> 27 <div id="five"></div> 28 </body> 29 </html>
遍历一个元素
1 <script type="text/javascript"> 2 $(function(){ 3 var obj = {name:"John",lang:"Java"}; 4 5 $.each(obj,function(key,value){ 6 alert("关键词:"+key+"==值:"+value); 7 }) 8 }) 9 </script>