1.$(selector).each(function(index,element))
2.$.each(dataresource,function(index,element))
接下来就对这两个函数做深入的探讨:
1.$(selector).each(function(index,element))
作用:在dom处理上面用的较多 (html 元素、节点)
示例:
遍历数组。html部分文档
<ul id="each_id">
<li>Coffee</li>
<li>Soda</li>
<li>Milk</li>
</ul>
js language-javascript">function traversalDOM(){
$("#each_id li").each(function(){
alert($(this).text())
});
}
输出结果:
2.$.each(dataresource,function(index,element))
作用:在数据处理上用的比较多
示例:
遍历JSON 对象。此处没有html代码,只有js代码,如下:
js language-javascript">function traversalData(){
var jsonResourceList =
'[{"id":"1","tagName":"apple"},
{"id":"2","tagName":"orange"},
{"id":"3","tagName":"banana"},
{"id":"4","tagName":"watermelon"}]';
//JSON.parse() 把json字符串转化为一个对象
//遍历JSON 数据
if(jsonResourceList.length >0){
$.each(JSON.parse(jsonResourceList),function(index,obj) {
alert(obj.tagName);
});
}
输出结果:
3.最终结论:
在遍历DOM时(如数组),通常用$(selector).each(function(index,element))函数;
在遍历数据时(如JSON 对象),通常用$.each(dataresource,function(index,element))函数。