简体   繁体   English

删除附加的父元素

[英]Removing an appended parent element

I have a list maker that appends items but also appends a trash can item to each of the list items which is made. 我有一个清单制造商,它可以附加项目,但也可以将垃圾桶项目附加到所制成的每个清单项目中。 I have a function on the trash can that should remove the parent element when it is clicked but it doesn't work. 我在垃圾桶上有一个函数,该函数应在单击父元素时将其删除,但不起作用。

Here is a simple version of what I'm trying to do 这是我正在尝试做的一个简单版本

JSFiddle JSFiddle

$('button').click(function() {
    $('#contain').append('<div class="div"></div>').append('<div class="nested"></div>');
});

$('.nested').click(function() {
    $(this).parent().remove();
});

How can I remove the parent element of only the nested div that is clicked? 如何删除仅单击的嵌套div的父元素?

Use on() because you're calling an event on dynamically appended element. 使用on()是因为您要在动态附加的元素上调用事件。

$('body').on('click', '.nested', function(){
   $(this).parent().remove();
});

Also we can use $('#contain') instead of $('body') as well. 我们也可以使用$('#contain')代替$('body')

 $('button').click(function() { $('#contain').append('<div class="div"></div>').append('<div class="nested"></div>'); }); $('body').on('click', '.nested', function() { $(this).parent().remove(); }); 
 .div { width: 100px; height: 50px; background: #000; margin-top: 50px; } .nested { width: 50px; height: 25px; background: red; z-index: 100; margin-top: -25px; cursor: pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Add </button> <div id="contain"> </div> 

try this: 尝试这个:

$('#contain').on('click', '.nested', function(){

});

you have to listen to clicks on the container for appended elements, since they're not in the DOM when the page is loaded 您必须听一下容器中附加元素的点击,因为加载页面时它们不在DOM中

Two issues: 两个问题:

  1. As the others have mentioned, you're binding your .nested click event before your element is created, meaning it won't have the event handler attached. 正如其他人提到的那样,您将创建元素之前绑定.nested click事件,这意味着它不会附加事件处理程序。 As the others mentioned, something like $("#contain").on("click", ".nested", function() {}) will fix the issue 正如其他人提到的那样,类似$("#contain").on("click", ".nested", function() {})之类的问题可以解决此问题。

  2. $.append returns the element you are appending to not the element being appended so your .nested is nested under the $("#contain") . $.append返回您要添加的元素, 不是要添加的元素因此您的.nested嵌套在$("#contain") This means the $(this).parent() is actually returning the #contain element. 这意味着$(this).parent()实际上返回了#contain元素。 A fix for the issue is 该问题的解决方法是

     $("<div class='nested' />").appendTo($("<div class='div' />").appendTo("#contain")); 

Change : 变更:

$('.nested').click(function() {
    $(this).parent().remove();
});

To: 至:

$(document).on("click",".nested",function(){

    $(this).parent().remove();

}) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM