1、$.each()--全局函数介绍
语法:全局函数 jQuery.each(collection,function(indexInArray,valueOfElement))
collection——可以是任何一个集合,不管是一个js对象或者一个数组,或者是一个json对象。
indexInArray——对象的键或者是数组的索引
valueOfElement——对象的值或者是数组的项
遍历一维数组
var arr = [‘a‘,‘b‘];
jQuery.each(arr,function(index,value){
console.log(index);
console.log(value);
})
结果:
遍历二维数组
var arr = [[‘a‘,‘b‘],[‘c‘,‘d‘]];
jQuery.each(arr,function(index,value){
jQuery.each(value,function(i,element){
console.log(i);
console.log(element);
})
})
结果:
遍历对象
var obj ={
name:‘zs‘,
age:18};
jQuery.each(obj,function(index,value){
console.log(index);
console.log(value);
})
结果:
遍历json对象
var obj = {"a":"hello", "b":"world"};
jQuery.each(obj,function(index,value){
console.log(index);
console.log(value);
})
结果:
1、$(selector).each()
语法:$(selector).each(function(index,value))
index ——伪数组的索引
value——伪数组的项值
在DOM上处理上面用的较多
遍历li标签
- 1
- 2
- 3
- 4
- 5
console.log(index);/*打印的是形如
1的字符串*/console.log(value);/*若是想输出标签中的数据,那么可以吧台看成DOM对象。然后用innerHTML方法,输出标签中的数据;也可以转化为
jQuery对象形如$(value).html(),然后在打印输出,如下:
// console.log($(value).html());*/console.log(value.innerHTML);
})
小结
遍历数据:jQuery.each(collection,function(indexInArray,valueOfElement));
遍历DOM:$(selector).each(function(index,value));