2012-06-09 72 views
1

我正在用jQuery寫一個Greasemonkey userscript。代碼片段影響論壇主題頁面,並打算在每個帖子的頁腳添加一個按鈕。jQuery .each(),.find()和.append()只在最後一個節點上工作?

假設按鈕已經是一個jQuery元素$button,這是我的代碼:

$('table.posts').each(function() { 
    //get the name of the poster 
    profileName = $(this).find('.user').text(); 
    //change the link relative to each poster 
    $button.attr('href', '/search?user=' + profileName); 
    //This is the problematic line: 
    $(this).find('div.postFooter').append($button); 
}); 

我一直在使用警報測試的profileName的價值,它成功地遍歷和警報配置文件名稱,但它只會將按鈕追加到最後一個帖子的頁腳(使用正確的鏈接)。

我已經使用了各種不同的選擇和方式遍歷DOM到所需的元素,嘗試過,但所有的方法都產生了同樣的事情。我沒有想法。

回答

3

使用clone

$(this).find('div.postFooter').append($button.clone(true)); 

每次你改變和附加相同$button元素。

+0

我稱之爲'.clone(真)'以防萬一還有的附加數據或事件處理程序,但除此之外,這看起來就像是問題的根源。 –

+0

@AnthonyGrist謝謝你的提問。我改變了我的答案。 – Engineer

+0

我不知道jQuery以這種方式處理對象。嘗試完美。非常感謝。 – azz

相關問題