2009-09-04 51 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); 

我不知道,如果你的代碼不能得到改善,但有當我只看到它的一小部分時,我可以說很少。