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

来源:互联网 发布:海关总署稽查司的数据 编辑:程序博客网 时间:2024/04/25 23:21

.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
原创粉丝点击