jQuery中each方法的使用详解
概述:
each()方法规定为每个匹配元素规定运行的函数。
返回false可用于及早停止循环,相当于break。
返回true可以结束本次循环,相当于continue。
语法:
$(selector).each(function(index,element){})
index-选择器的index位置
element-当前的元素(也可使用"this"选择器)
$(selector).each(function(){})
$.each(array,function(Key,Value){})
1.遍历js数组
$(function(){
vararray=["aaa","bbb","ccc"];
$.each(array,function(i,j){
alert(i+":"+j);//i表示索引,j代表值
});
})
2.遍历Object对象
varobj=newObject();
obj.name="zs";
$.each(obj,function(name,value){
alert(this);//this指向当前属性的值,等价于value
alert(name);//name表示Object当前属性的名称
alert(value);//value表示Object当前属性的值
});
3.遍历JSON对象
varjson={"name":"zhangSan","role":"student"};
$.each(json,function(key,value){
alert(key+":"+value);
});
4.遍历由多个JSON对象组成的数组
varjson=[{"name":"Amy","role":"student"},{"name":"Tom","role":"student"}];
$.each(json,function(index,value){
alert("index="+index+"\n"+"name:"+value.name+"\n"+"role:"+value.role+"\n");
});
5.遍历jQuery对象
遍历jQuery对象 $(function(){ $("input[type='button']").bind("click",function(){ $("li").each(function(){ alert($(this).text()) }); }); });
- first
- second
总结
以上所述是小编给大家介绍的jQuery中each方法的使用详解,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!