gpt4 book ai didi

jquery - 类未添加到单击事件处理程序中

转载 作者:行者123 更新时间:2023-12-01 06:27:51 24 4
gpt4 key购买 nike

我正在学习 jQuery,但在使用 .on() 事件处理程序时遇到问题。我不知道为什么类 done 没有被添加到动态添加的新列表项中。任何援助将不胜感激。 jsFiddle

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
ul li{
list-style: none;
}
.done{
text-decoration: line-through;
color: red;
}
.green{
color:green;
}
</style>
</head>
<script type="text/javascript">
$(document).ready(function(){
$('#taskText').keydown(function(evt){
if(evt.keyCode == 13){
addTask(this, evt);
}
});
$('#addTask').click(function(evt){
addTask(document.getElementById('taskText'), evt);
});
//the problem is the code below//

$('#tasks li').on("click", function(evt){
$(this).addClass('done');
});
});
function addTask(textBox, evt){
evt.preventDefault();
var taskText = textBox.value;
$("<li>").text(taskText).appendTo('#tasks');
textBox.value = '';
};
</script>
<body>



<ul id = "tasks">

</ul>
<input type= 'text' id ='taskText'>
<input type = 'submit' id ="addTask" />
<div class = "green"> green text</div>
</body>
</html>

最佳答案

您需要指定that optional selector argument for .on()适用于事件绑定(bind)后创建的元素:

$('#tasks').on('click', 'li', function(evt){
$(this).addClass('done');
});

直接来自 API 文档:

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 - 类未添加到单击事件处理程序中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14766719/

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