Javascript 使用删除函数。这不起作用
这是我创建的演示 在该链接中,“删除父对象”正在工作。但是,“删除子对象”功能不起作用 以下是我使用的代码:Javascript 使用删除函数。这不起作用,javascript,Javascript,这是我创建的演示 在该链接中,“删除父对象”正在工作。但是,“删除子对象”功能不起作用 以下是我使用的代码: $('.dec-child').on('click', function(){ $(this.parent('.child:last').remove()); }) 您应该使用jQuery包装this,以便它返回jQuery对象 $('.dec-child').on('click', function(){ $(this).parent('.child:last').r
$('.dec-child').on('click', function(){
$(this.parent('.child:last').remove());
})
您应该使用
jQuery
包装this
,以便它返回jQuery对象
$('.dec-child').on('click', function(){
$(this).parent('.child:last').remove();
});
您没有正确关闭
此
应该是
$(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();
})
上面的代码不适用于您,因此请尝试此操作,您的代码将正常工作 您的代码不起作用,因为
不是
的父级,在我们的例子中,您应该这样使用
$(document).on('click', '.dec-child', function() {
$(this).siblings('.child:last').remove();
})
如果使用parent()
$(document).on('click', '.dec-child', function() {
$(this).parent().find('.child:last').remove();
})
将您的功能更改为
$('.dec-child').on('click', function(){
$(this).parent().parent().find('.child').last().remove();
})
请参阅jsfiddle我试图正确关闭它。这是一个动态创建父元素的演示:伙计们,我该怎么做??你们都是伟大的程序员。我第一次只接受了他的回答。请不要为此争吵。原谅我…在对第二个家长执行此操作时出现问题@在这种情况下,您必须使用事件委托。因为按钮是动态添加的,所以它必须使用事件委派来侦听事件。请查看我的答案中的示例是的,如果您创建的按钮是动态的,那么您不能调用该按钮的单击功能。“所以更新你的js文件也许这把小提琴会有帮助,这是正确的答案,每个人……工作都很好,@Alexander。”。