jquery的$().each,$.each的区别

jquery的$().each,$.each的区别

1.$(selector).each(function(index,element))
2.$.each(dataresource,function(index,element))

1.$(selector).each(function(index,element))

作用:在dom处理上面用的较多

示例:

html部分文档

<ul id="each_id">

	<li>Coffee</li>

	<li>Soda</li>

	<li>Milk</li>

</ul>

js遍历函数:


function traversalDOM(){

$("#each_id li").each(function(){

      alert($(this).text())

    });

}

2.$.each(dataresource,function(index,element))

作用:在数据处理上用的比较多

示例:

此处没有html代码,只有js代码,如下:

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);

	});	

}

结论:

在遍历DOM时,通常用$(selector).each(function(index,element))函数;

在遍历数据时,通常用$.each(dataresource,function(index,element))函数。

猜你喜欢

转载自my.oschina.net/shuaihong/blog/1790015