2013-06-21 49 views
0

我想要刪除每個具有相同類元素的選定元素。我的jQuery的編碼波紋管jquery每個函數和單擊事件不起作用

$(".del_layer").each(function(){  $(this).click(function(){ 
      $(this).parent().remove(); 
       }); 

      }); 

我的HTML結構給出的是

<li class="select_layerList" data-refind="0"> 
<img width="20px" src="tmp_card_imgs/a.png"> 
Layer 0:Image 
<span class="del_layer" style="cursor:pointer;">X</span> 
</li> 
<li class="select_layerList" data-refind="0"> 
<img width="20px" src="tmp_card_imgs/b.png"> 
Layer 0:Image 
<span class="del_layer" style="cursor:pointer;">X</span> 
</li> 

但是每個功能無法正常工作。 我怎樣才能解決這個

+1

你並不需要保持你的'。點擊()''的。每個()'裏面。 –

+0

對我而言看起來很好http://jsfiddle.net/arunpjohny/hcB4T/1/ –

回答

0

您可以刪除每個功能,因爲你可以通過類名稱來選擇它們,並把你的腳本上的文檔準備像

$(document).ready(function(){ 
    $('.del_layer').on('click',function(){ 
     $(this).parent().remove(); 
    }); 
}); 
0

爲什麼不嘗試這樣的事情

$(".del_layer").on('tap',function(){ 
    $(this).parent().remove(); 
}); 
+1

現場已棄用 –

+0

是的,我將它改爲ON – Rajeev

1

它工作正常。

http://jsfiddle.net/4LeuA/

確保您有DOM加載,把你的代碼中一個document.ready()

$(document).ready(function() { 

}); 
+0

是我的jquery代碼在$(document).ready(function(){} –

0

沒有必要通過.each()遍歷,只是將事件套用到選擇並刪除其母公司:

$(".del_layer").click(function(){ 
    $(this).parent('li').remove(); 
}); 

並且您可以使用.closest()函數遍歷u p給所需的父母。

$(".del_layer").click(function(){ 
    $(this).closest('li').remove(); 
}); 
0

使用事件代表團,您可以設置相同的處理一次:

$(document).on('click', '.del_layer', function() { 
    $(this).parent().remove(); 
});