2009-10-30 88 views
27

我有以下代码:删除最后追加元件的jquery

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

现在我想删除最后所附元件(的图像)。请提出建议。

回答

32

可以使用:last-child选择找到最后附加元素,那么你可以remove它:

$('img:last-child', this).remove(); 
// get the last img element of the childs of 'this' 
14

从原来的问题的代码可能会产生错误(使用“本”与选择)。尝试以下方法:

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

如果我们要删除所有我们附加上一次的元素? – 2013-02-19 12:14:09

+0

您可能想避免使用表达式“上述代码”,因为这可能会改变。 – StubbornShowaGuy 2016-09-21 08:35:17

+0

谢谢 - 修正了(多年后) – eugene 2017-06-26 04:12:29

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;" />' 
); 
4

太棒了,非常感谢eugene,真的帮了我很大的忙。我不得不删除一张桌子,我使用了下面的代码。

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

这应该是对eugene答案的评论,而不是单独的答案本身。 – gtmtg 2012-08-08 20:13:02

34

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

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