2012-06-09 70 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

相关问题