概述:
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(){ var array=[aaa,bbb,ccc]; $.each(array,function(i,j){ alert(i+:+j);//i表示索引,j代表值 }); })
2.遍历object对象
var obj = new object(); obj.name=zs; $.each(obj, function(name, value) { alert(this); //this指向当前属性的值,等价于value alert(name); //name表示object当前属性的名称 alert(value); //value表示object当前属性的值 });
3.遍历json对象
var json ={name:zhangsan,role:student}; $.each(json,function(key,value){ alert(key+:+value); });
4.遍历由多个json对象组成的数组
var json =[{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对象
<head> <meta charset="utf-8" /> <title>遍历jquery对象</title> <script src="js/jquery-1.12.4.js"></script> <script type="text/javascript"> $(function(){ $(input[type='button']).bind(click,function(){ $(li).each(function(){ alert($(this).text()) }); }); }); </script> </head> <body> <input type="button" value="触发事件"/> <ul> <li>first</li> <li>second</li> </ul> </body>
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
jquery替换节点元素步骤详解
servlet3.0与js通过ajax交互实例详解
以上就是jquery里each方法使用案例的详细内容。
