gpt4 book ai didi

jquery - 如何在 jQuery 中使用 .click 和 .remove 删除元素

转载 作者:行者123 更新时间:2023-11-28 04:22:16 26 4
gpt4 key购买 nike

这是 JSfiddle

这是我的代码。

HTML

<h2>Todo List</h2>
<div id='additem'>
<input type='text' name='additem'/>
<button>Add Item</button>
</div>
<div id='todolist'>
<ol>
</ol>
<!-- Add item from "additem" input field -->
</div>

JS

$(document).ready(function(){
$('button').click(function(){
var item = $('input[name=additem]').val();
$('ol').append('<li>'+ item +' <button id="remove">Remove</button></li>');
});
$("#remove").click(function(){
$(this).parent('li').remove();
});

});

最佳答案

您需要使用 on()对于使用事件委托(delegate)动态添加的元素。您可以将事件委托(delegate)给使用 on 绑定(bind)事件时可用的 parent 元素,否则您可以使用 document

$(document).on("click", "#remove", function(){
$(this).parent('li').remove();
});

委托(delegate)事件

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, Reference

关于jquery - 如何在 jQuery 中使用 .click 和 .remove 删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16448042/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com