jQuery .each()、.find() 和 .append() 只在最后一个节点上工作

jQuery .each(), .find() and .append() only working on the last node?

本文关键字:最后一个 节点 工作 each find jQuery append      更新时间:2023-09-26

我正在用jQuery编写一个Greasemonkey用户脚本。代码段会影响论坛主题页面,并打算在每个帖子的页脚后附加一个按钮。

假设按钮已经是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 到所需的元素,但所有方法都产生了相同的结果。我没主意了。

使用克隆:

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

每次更改和附加相同的$button元素时。