gpt4 book ai didi

jQuery - 选择动态创建的 div

转载 作者:行者123 更新时间:2023-12-01 00:15:22 26 4
gpt4 key购买 nike

我有一个简单的 jQuery 问题:

首先,我的 HTML:

<div id="taskinput">
<form>
<input id="taskinput-box" type="text"></input>
<input type="submit"></input>
</form>
</div><!-- end taskinput -->
<div id="taskoutput"></div><!-- end taskoutput -->

我在创建新类 .task 时使用 .append 在 #taskoutput 中创建用户的内容。

$("#taskinput").submit(function() {
var tasktext = $('#taskinput-box').val()
$('#taskoutput').append('<div class="task">'+tasktext+'</div>');
$('#taskinput-box').val("");
return false;
});

上面的代码工作正常;当我尝试选择创建的 div 时出现问题。下面的代码不起作用:

$(".task").click(function() {
$(this).slideUp();
});

我错过了什么?

最佳答案

您必须使用委托(delegate)事件,例如on:

$('#taskoutput').on('click', '.task', function(){
$(this).slideUp();
});

@salek DEMO开启

阅读on docs :

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

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, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

关于jQuery - 选择动态创建的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10712051/

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