0

我想删除每个具有相同类元素的选定元素。我的 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>

但是每个功能都不起作用。我该如何解决这个问题

4

5 回答 5

1

它工作正常。

http://jsfiddle.net/4LeuA/

确保你DOM已经加载了,把你的代码放在一个document.ready()

$(document).ready(function() {

});
于 2013-06-21T09:42:25.517 回答
0

您可以删除每个函数,因为您可以通过类名选择它们并将脚本放在准备好的文档中,例如

$(document).ready(function(){
    $('.del_layer').on('click',function(){
        $(this).parent().remove();
    });   
});
于 2013-06-21T09:41:14.900 回答
0

为什么不尝试这样的事情

 $(".del_layer").on('tap',function(){
  $(this).parent().remove();
 });
于 2013-06-21T09:42:08.017 回答
0

无需遍历.each(),只需将事件应用到选择器并移除其父级即可:

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

您可以使用.closest()函数遍历到所需的父级。

$(".del_layer").click(function(){
    $(this).closest('li').remove();
});
于 2013-06-21T09:45:40.537 回答
0

使用事件委托,您可以设置一次相同的处理程序:

$(document).on('click', '.del_layer', function() {
  $(this).parent().remove();
});
于 2013-06-21T09:46:03.100 回答