【问题标题】:jQuery append child nodes in for eachjQuery为每个附加子节点
【发布时间】:2010-11-25 15:40:13
【问题描述】:

在下面的代码中,我试图遍历每个子节点并将子节点附加到另一个元素 - 循环内的正确语法是什么?

$(this).children().each(    
    $(div).appendChild(this.childNodes.length - 1);
);

【问题讨论】:

    标签: jquery foreach


    【解决方案1】:

    each() 函数中,this 指的是您正在迭代的对象,在本例中为children()。这不是原始 jQuery 对象的this

    因此:

    $(this).children().each(function() {    
        $(div).appendChild($(this));
    });
    

    【讨论】:

      【解决方案2】:

      你应该在each调用中使用函数回调或匿名函数:

      $(this).children().each(function() {
          $(div).appendChild(this.childNodes.length - 1);
      });
      

      function doSomething() {
          $(div).appendChild(this.childNodes.length - 1);
      }
      
      $(this).children().each(doSomething);
      

      我不确定您的代码是否无法改进,但当我只看到其中的一小部分时,我无话可说。

      【讨论】:

        猜你喜欢
        • 2020-03-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-15
        • 1970-01-01
        • 1970-01-01
        • 2014-12-15
        • 2017-01-16
        相关资源
        最近更新 更多