jQuery中两种遍历$.each()
和$().each()
的区别
1. $.each()
同java中的for循环类似,传入一个数组或集合就可以遍历出其属性
1.1 遍历一维数组
var arr1 = [ "one", "two", "three", "four", "five" ];
$.each(arr1, function(){
alert(this);
});
//输出:one two three four five
1.2 遍历二维数组
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
$.each(arr2, function(i, item){ //i为二维数组下标,item为当前下标对应的值
alert(item[0]);
});
//输出:1 4 7
1.3 遍历Json格式数组
var obj = { one:1, two:2, three:3, four:4, five:5 };
$.each(obj, function(key, val) { //key为json下标,通过key取出value值
alert(obj[key]);
});
//输出:1 2 3 4 5
2. $().each()
- 语法:
$(selector).each(function(index,element))
selector
:jQuery选取的元素index
:选择器index的位置element
:当前的元素
- 范例:
//遍历所有name属性为"ch"的input元素
$(“input[name=’ch’]”).each(function(i){
if($(this).attr(‘checked’)==true) {
//一些操作代码
}
}