• jquery的$().each和$.each的区别


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

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

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

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

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

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

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

    1
    2
    3
    4
    5
    <ul id="each_id">
      <li>muzi</li>
      <li>digbig</li>
      <li>muzidigbig</li>
    </ul>

    js遍历函数:

    1
    2
    3
    4
    5
    6
    function traversalDOM(){
      $("#each_id li").each(function(){
         alert($(this).text())
      });
    }
    traversalDOM();

    输出结果:

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

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

    示例:

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    function traversalData(){
      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, currentObj) {
          alert(currentObj.tagName);
        });
      }
    }
    traversalData()

    3.最终结论:

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

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

  • 相关阅读:
    Android 使用MediaPlayer 播放 视频
    Android加载asset的db
    MAC SVN 基本设置 终端命令
    AFNetWork 简单实用demo
    IntelliJ IDEA导出Java 可执行Jar包
    Xcode快速排错
    Listview多tab上滑悬浮
    N最短路径分词
    进程监控工具supervisor
    nginx配置指南
  • 原文地址:https://www.cnblogs.com/newones/p/12678375.html
Copyright © 2020-2023  润新知