使用删除函数.这不起作用

Remove function using .this is not working

本文关键字:不起作用 函数 删除      更新时间:2023-09-26

这是我创建的演示链接。

在该链接中,"删除父项"正在工作。但是,"删除子项"功能不起作用。

这是我使用的代码:

$('.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();
  });

我将您的代码更改为

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

上面的代码不适合你,所以尝试一下,你的代码就会正常工作。

您的代码不起作用,因为<div class="child"></div>不是<a href="#" class="dec-child">remove previous Child</a>的父级,在我们的情况下,您应该使用siblings,就像一样

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

示例

如果你使用parent(),你就会得到<div class="parent">,所以你需要在这个div中找到.child类的元素,你可以这样做

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

示例

您应该用jQuery包装this,这样它就会返回一个jQuery对象。

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

将函数更改为

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

请参考jsfiddlehttp://jsfiddle.net/mrvtwpjp/22/