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


    最近一直在研究JS,今天看到遍历模块的时候,看到了这个函数:

    $(selector).each(function( ))

    但是想想,这个函数和之前项目里面用到的遍历数据的函数不是同一个呀(项目里面用到的函数:$.each(dataresource,function(index,element))),于是,就好好研究了下,果然在JS里面有两个相似的函数,于是也就有了今天的主题:

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

    接下来就对这两个函数做深入的探讨:

    1.$(selector).each(function( ))

    作用:在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代码,如下:

    function traversalData(){
    var jsonResourceList = '[{"id":"1","tagName":"apple"},{"id":"2","tagName":"orange"},{"id":"3","tagName":"banan a"},{"id":"4","tagName":"watermelon"}]';
    if(jsonResourceList.length >0){
    $.each(JSON.parse(jsonResourceList), function(index, obj) {
        alert(obj.tagName);
    });
    }
    }

    输出结果:

    3.最终结论:

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

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

    好了,就到这里吧,希望可以帮助到大家!

  • 相关阅读:
    Mysql 视图用途、使用场景、性能问题及使用注意事项
    深入解析MySQL视图VIEW
    delete语句的基本用法
    update语句基本用法
    mysql插入中文数据变成问号怎么处理
    MySQL数据表中有自增长主键时如何插入数据
    INSERT INTO语句的基本用法
    mysql HAVING用法
    mysql关于group by的用法
    python模拟鼠标拖动教程
  • 原文地址:https://www.cnblogs.com/hangaozu/p/7773128.html
Copyright © 2020-2023  润新知