Jquery:无法删除动态创建的元素 [英] Jquery : Can't remove element dynamically created
问题描述
我正在尝试删除动态追加的元素,但似乎没有读取为此元素附加的类函数。
I'm trying to remove a dynamically appended element, but it seems that the class function attached for this element is not read.
我可以点击+按钮添加新元素,但点击 - 按钮后我无法删除。
I can click on + button and add new elements, but I can't delete when clicking on "-" button.
<div id="dftenglist">
<label for="dtfeng">Name:</label><input type="text" class="dfteng">
<button id="plusdfteng">+</button>
</div>
$("#plusdfteng").click(function() {
$("#dftenglist").append('<br><span><label for "a">Name:</label><input type="text" class="dfteng"> <button class="minusbtn">-</button></span>');
});
$(".minusbtn").click(function() {
$(this).parent().remove();
})
http: //jsfiddle.net/0uv4k5bz/1/
谢谢,
Alex
Thanks, Alex
推荐答案
在此上下文中尝试使用 event-delegation
,
Try to use event-delegation
at this context,
$("#dftenglist").on("click", ".minusbtn", function() {
$(this).parent().remove();
});
DEMO
您可能会问为什么?原因是,在向该特定元素注册事件时,该元素将由于我们在运行时添加它,因此无法在DOM中使用。因此,在这种情况下,事件委托
将利用幕后的事件冒泡概念来解决这个问题。有关详细信息,请在此处阅读。
DEMO
You may ask why? The reason is, while registering event to that particular element, that element will not be available at the DOM since we are adding it at the runtime. So at that case event-delegation
will make use of the event-bubbling concept under the hood to over come this issue. For more info read here.
对于您的新要求,请执行以下操作,删除父元素时删除< br>
。
For your new requirement just do like below, remove the <br>
while removing the parent element.
$("#dftenglist").on("click", ".minusbtn", function () {
$(this).parent().prev('br').addBack().remove();
});
这篇关于Jquery:无法删除动态创建的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!