您的位置:首页 > 其它

$.each()函数与$(selector).each()的区别

2017-12-21 09:10 507 查看
.each()functionisnotthesameas(selector).each(), which is used to iterate, exclusively, over a jQuery object. The .each()functioncanbeusedtoiterateoveranycollection,whetheritisanobjectoranarray.Inthecaseofanarray,thecallbackispassedanarrayindexandacorrespondingarrayvalueeachtime.(Thevaluecanalsobeaccessedthroughthethiskeyword,butJavascriptwillalwayswrapthethisvalueasanObjectevenifitisasimplestringornumbervalue.)Themethodreturnsitsfirstargument,theobjectthatwasiterated.官方的解释:.each()函数与(selector).each()不同,后者用于对jQuery对象进行迭代。.each()函数可以用于遍历任何集合,无论它是对象还是数组。在数组的情况下,每次回调都会传递一个数组索引和相应的数组值。(这个值也可以通过这个关键字来访问,但是Javascript总是将这个值作为一个对象包装,即使它是一个简单的字符串或数字值。)该方法返回第一个参数,即迭代的对象。

(selector).each():函数传递的参数可以是一个也可以是两个(selector).each(function(index, Element) );第一个参数代表数组的索引,第二个参数代表数组里面对应的值。

<ul>
<li>foo</li>
<li>bar</li>
</ul>
你可以选中并迭代这些列表:

$( "li" ).each(function( index ) {
console.log( index + ": "" + $(this).text() );
});
列表中每一项会显示在下面的消息中:

0: foo
1: bar

我们可以通过返回 false以便在回调函数内中止循环。

参数代表的意思:

<ul>
<li>foo</li>
<li>bar</li>
</ul>

<script>
$( "li" ).each(function( index ,dom ) {
console.log(index);// 0 ,1
console.log(dom);// <li>foo</li>
console.log($(dom).text());//foo
})
</script>


$.each()函数既可以遍历数组又可以遍历对象

遍历数组
$.each([ 52, 97 ], function( index, value ) {
alert( index + ": " + value );
});
输出结果
0: 52
1: 97

遍历对象
var obj = {
"flammable": "inflammable",
"duh": "no duh"
};
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
输出结果
flammable: inflammable
duh: no duh
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  each jq 遍历 对象 数组