1.each函数
each() 函数规定为每个匹配元素规定运行的函数。
1.1.配合选择器
$(selector).each(function(index,element))
将所有图像标签的类型地址改成JPG.jpg图片。其中element可以用this替代,源代码如下所示:
$("Img").each(function(i,ele){
$(ele).attr("src","../Img/JPG.jpg");
//或者
$(this).attr("src","../Img/JPG.jpg");
})
1.2.读取数组数据
遍历数组数据。
$.each(dataresource,function(index,element))
function traversalData(){
var jsonResourceList = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},{"id":"3","tagName":"banana"},{"id":"4","tagName":"watermelon"}]';
if(jsonResourceList.length >0){
$.each(JSON.parse(jsonResourceList), function(index, obj) {
alert(obj.tagName);
});
}
}
2.forEach函数
forEach() 方法对数组的每个元素执行一次提供的函数。
[ ].forEach(function(value,index,array){code;});
第一个参数是遍历的数组内容,
第二个参数是对应的数组索引,
第三个参数是数组本身
var arr = [1,2,3,4];
var sum =0;
arr.forEach(function(value,index,array){
array[index] == value; //结果为true
sum+=value;
});
console.log(sum); //结果为 10
3.作者答疑
如有疑问,敬请留言。