jQuery遍历数组
数组遍历:
在JS中,我们使用普通for循环即可遍历数组。
在jQuery中,我们可以使数组的遍历变得更为简单(使用for遍历,取出的元素为js对象而非jQuery对象)
属性名 | 属性说明 |
JQ数组.each(fn); | 遍历jQuery数组 |
$.each(jQuery数组,fn); | 遍历jQuery数组 |
代码演示:
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title></title><script type="text/javascript" src="../js/jquery.js" ></script><script>$(function(){//方式1alert("方式1:普通遍历");var dd = $("div");for(var i=0;i<dd.length;i++){alert(dd[i].innerHTML);}//方式2//索引从0开始alert("方式2:jq遍历1");var dd = $("div");//这里的index是一个循环因子,可以任意起名,相当于是之前的i//下面的this是规定的,功能类似JAVA中继承中的thisdd.each(function(index){alert(index+"<<>>"+$(this).html());});//方式3alert("方式3:jq遍历2");var dd = $("div");$.each(dd,function(index){alert(index+"<<>>"+$(this).html());});//使用$.each() 遍历普通的js数组alert("使用$.each() 遍历普通的js数组");var arr = ['aaa','bbb',123,3.12];$.each(arr, function(index) {alert(index+"<<>>"+this); });})</script></head><body><div>111111</div><div>222222</div><div>333333</div><div>444444</div></body>
</html>