我刚刚开始学习 HTML、CSS 和 jQuery,而且我是新手。我搜索了将事件处理程序绑定(bind)到动态添加的元素,发现我必须使用动态元素的父级作为静态选择器,并在事件方法之后添加动态元素(如果我错了,请纠正我)。
$(staticAncestors).on(eventName,dynamicChild,function(){});
但我不知道为什么下面的代码在我更改时不起作用:
$("#p1")
与$(this)
或$(document)
与$("div")
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("div").click(function(){
$(this).html('<p id="p1" style="background: red;">Paragraph one</p> <p>Paragraph two</p>').css('margin', '15px 15px 15px 15px');
});
$(document).on('click', '#p1', function(){
$("#p1").css('background-color', 'blue');
});
});
</script>
</head>
<body>
<div> It's a div. </div>
</body>
</html>
最佳答案
根据 Jquery 文档 https://api.jquery.com/on/
By default, most events bubble up from the original event target to the document element (In your case from #p1). At each element along the way, jQuery calls any matching event handlers that have been attached. A handler can prevent the event from bubbling further up the document tree (and thus prevent handlers on those elements from running) by calling event.stopPropagation().
这是您的工作代码。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("div").click(function(){
$(this)
.html('<p id="p1" style="background: red;">Paragraph one</p> <p>Paragraph two</p>')
.css('margin', '15px 15px 15px 15px');
});
$("div").on('click', 'p', function(event){
event.stopPropagation();
$(this).css('background-color', 'blue');
});
});
</script>
</head>
<body>
<div> It's a div. </div>
</body>
</html>
关于jquery - 将事件处理程序绑定(bind)到动态创建的元素时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64452260/