删除最后一个追加的元素jQuery

38

我有以下代码:

$(this).children("a:eq(0)").append('<img src="'+ (arrowsvar.down[1]) 
    +'" class="' + (arrowsvar.down[0])
    + '" style="border:0;" />'
);

现在我想删除最后添加的元素(一张图片)。 请给出建议。

5个回答

58

作为替代方案,对于那些更喜欢编程方式和语法的人:

$('#container-element img').last().remove();

36
您可以使用:last-child选择器找到最后添加的元素,然后可以删除它: :last-childremove
$('img:last-child', this).remove();
// get the last img element of the childs of 'this'

20

原问题的代码可能会生成错误(在选择器中使用“this”)。尝试以下方法:

$("#container-element img:last-child").remove()

如果我们想要删除上一次添加的所有元素,应该怎么做? - Php Geek
您可能希望避免使用表达式“上述代码”,因为它可能会发生变化。 - StubbornShowaGuy

6

太棒了,非常感谢Eugene,这真的帮了我很多。我必须删除一个表格,我使用了以下代码。

$("#mydivId table:last-child").remove()

3
这应该是对 Eugene 回答的评论,而不是独立的答案。 - gtmtg

2
尝试这个。只需添加 .not(':last-child'),它将排除您的集合中的最后一个元素。因此,您不必将其删除。
$(this).children("a:eq(0)").not(':last-child').append('<img src="'+ (arrowsvar.down[1]) 
    +'" class="' + (arrowsvar.down[0])
    + '" style="border:0;" />'
);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接