2015-04-07 64 views
-2

這是我創建的演示link刪除功能使用。這不起作用

在該鏈接中,「刪除父母」正在工作。但是,「刪除孩子」功能不起作用。

這裏是我使用的代碼:

$('.dec-child').on('click', function(){ 
    $(this.parent('.child:last').remove()); 
}) 
+0

可能是這樣的小提琴將有助於http://jsfiddle.net/wpppLyek/ –

+0

[這裏](HTTP:/ /jsfiddle.net/mrvtwpjp/27/)是正確的答案,每個人... – ARUN

回答

2

您尚未正確關閉this

應該

$(this).parent('.child:last').remove(); 

而且選擇是錯誤的。

關於.dec-child,.child是兄弟姐妹,而不是父母。

$(this).siblings('.child:last').remove(); 

DEMO

如果你想使之成爲所有動態添加的子元素則必須使用事件委託的工作。

$('body').on('click',".dec-child", function(){ 
     $(this).siblings('.child:last').remove(); 
    }); 
+0

我試着正確關閉它,[這裏](http://jsfiddle.net/mrvtwpjp/8/)。還是行不通。 – ARUN

+0

演示:http://jsbin.com/yajuwizibe/1/edit?html,css,js輸出 – mohamedrias

+0

這裏是一個演示動態創建的父元素:http://jsbin.com/tigahafina/1/edit?html,css,js,輸出 – mohamedrias

0

你應該只是包裝thisjQuery所以它返回一個jQuery對象。

$('.dec-child').on('click', function(){ 
    $(this).parent('.child:last').remove(); 
}); 
+0

試過。仍然,不工作 – ARUN

1

我改變你的代碼

$('.dec-child').on('click', function(){ 
    $(this).parent().find('.child:last').remove(); 
}) 

上面的代碼將不會爲你工作,那麼試試這個,你的代碼將正常工作。

+0

在第二個家長這樣做時遇到問題。 [這裏](http://jsfiddle.net/mrvtwpjp/15/)。 – ARUN

+0

@你需要在這種情況下使用事件委託。由於該按鈕是動態添加的,所以它必須使用事件委託來監聽事件。請檢查我的答案 – mohamedrias

+0

是的,如果您創建的按鈕是動態的,那麼您無法調用該按鈕的點擊功能。所以更新你的js文件 –

1

您的代碼不起作用,因爲<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(); 
}) 

Example

在這個div類中找到類.child,你可以這樣做

$(document).on('click', '.dec-child', function() { 
    $(this).parent().find('.child:last').remove(); 
}) 

Example

+0

偉大的工程,@亞歷山大。 – ARUN

0

你的函數改爲

$('.dec-child').on('click', function(){ 
     $(this).parent().parent().find('.child').last().remove(); 
    }) 

請參閱的jsfiddle http://jsfiddle.net/mrvtwpjp/22/

+0

不適用於第二個家長 – ARUN