2009-09-04 69 views
5

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

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

回答

8

each()函数中,this指的是你正在迭代的东西,在这种情况下是children()。这不是原始jQuery对象的this

因此:

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

你应该each通话使用回调函数或匿名函数:

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

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

$(this).children().each(doSomething); 

我不知道,如果你的代码不能得到改善,但有当我只看到它的一小部分时,我可以说很少。