2009-10-30 60 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();