這是我創建的演示link。刪除功能使用。這不起作用
在該鏈接中,「刪除父母」正在工作。但是,「刪除孩子」功能不起作用。
這裏是我使用的代碼:
$('.dec-child').on('click', function(){
$(this.parent('.child:last').remove());
})
這是我創建的演示link。刪除功能使用。這不起作用
在該鏈接中,「刪除父母」正在工作。但是,「刪除孩子」功能不起作用。
這裏是我使用的代碼:
$('.dec-child').on('click', function(){
$(this.parent('.child:last').remove());
})
您尚未正確關閉this
。
應該
$(this).parent('.child:last').remove();
而且選擇是錯誤的。
關於.dec-child
,.child
是兄弟姐妹,而不是父母。
$(this).siblings('.child:last').remove();
如果你想使之成爲所有動態添加的子元素則必須使用事件委託的工作。
$('body').on('click',".dec-child", function(){
$(this).siblings('.child:last').remove();
});
我試着正確關閉它,[這裏](http://jsfiddle.net/mrvtwpjp/8/)。還是行不通。 – ARUN
演示:http://jsbin.com/yajuwizibe/1/edit?html,css,js輸出 – mohamedrias
這裏是一個演示動態創建的父元素:http://jsbin.com/tigahafina/1/edit?html,css,js,輸出 – mohamedrias
你應該只是包裝this
與jQuery
所以它返回一個jQuery對象。
$('.dec-child').on('click', function(){
$(this).parent('.child:last').remove();
});
試過。仍然,不工作 – ARUN
我改變你的代碼
$('.dec-child').on('click', function(){
$(this).parent().find('.child:last').remove();
})
上面的代碼將不會爲你工作,那麼試試這個,你的代碼將正常工作。
在第二個家長這樣做時遇到問題。 [這裏](http://jsfiddle.net/mrvtwpjp/15/)。 – ARUN
@你需要在這種情況下使用事件委託。由於該按鈕是動態添加的,所以它必須使用事件委託來監聽事件。請檢查我的答案 – mohamedrias
是的,如果您創建的按鈕是動態的,那麼您無法調用該按鈕的點擊功能。所以更新你的js文件 –
您的代碼不起作用,因爲<div class="child"></div>
不是<a href="#" class="dec-child">remove previous Child</a>
父母,在我們的情況下,如果你使用parent()
你<div class="parent">
,所以你需要,你應使用siblings
,像這樣
$(document).on('click', '.dec-child', function() {
$(this).siblings('.child:last').remove();
})
在這個div類中找到類.child
,你可以這樣做
$(document).on('click', '.dec-child', function() {
$(this).parent().find('.child:last').remove();
})
偉大的工程,@亞歷山大。 – ARUN
你的函數改爲
$('.dec-child').on('click', function(){
$(this).parent().parent().find('.child').last().remove();
})
請參閱的jsfiddle http://jsfiddle.net/mrvtwpjp/22/
不適用於第二個家長 – ARUN
可能是這樣的小提琴將有助於http://jsfiddle.net/wpppLyek/ –
[這裏](HTTP:/ /jsfiddle.net/mrvtwpjp/27/)是正確的答案,每個人... – ARUN