jQuery 中的 $().each 和 $.each 的区别是什么? 下面本篇文章就来给大家介绍一下. 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
在 jQuery 中, 遍历对象和数组, 经常会用到 $().each 和 $.each(), 两个方法. 两个方法是有区别的, 从而这两个方法在针对不同的操作上, 显示了各自的特点.
1,$(selector).each(function(index,element))
作用: 在 dom 处理上面用的较多
- <ul id="each_id">
- <li>muzi</li>
- <li>digbig</li>
- <li>muzidigbig</li>
- </ul>
JS 遍历函数:
- function traversalDOM(){
- $("#each_id li").each(function(){
- alert($(this).text())
- });
- }
- traversalDOM();
输出结果:
2,$.each(dataresource,function(index,element))
作用: 在数据处理上用的比较多
示例:
此处没有 html 代码, 只有 JS 代码, 如下:
- 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, currentObj) {
- alert(currentObj.tagName);
- });
- }
- }
- traversalData()
3, 最终结论:
在遍历 DOM 时, 通常用 $(selector).each(function(index,element)) 函数;
在遍历数据时, 通常用 $.each(dataresource,function(index,element)) 函数.
想要进行更多 web 前端学习 https://www.html.cn/ , 请访问 HTML 中文网 !!
来源: http://www.css88.com/qa/jquery/16425.html