jquery - 将事件处理程序绑定(bind)到动态创建的元素时出现问题

标签 jquery

我刚刚开始学习 HTML、CSS 和 jQuery,而且我是新手。我搜索了将事件处理程序绑定(bind)到动态添加的元素,发现我必须使用动态元素的父级作为静态选择器,并在事件方法之后添加动态元素(如果我错了,请纠正我)。
$(staticAncestors).on(eventName,dynamicChild,function(){});
但我不知道为什么下面的代码在我更改时不起作用:

  1. $("#p1") $(this)
  2. $(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/

相关文章:

javascript - Skrollr 无法在移动设备上运行

javascript - 类似 Reactjs 的动画库?

javascript - (jQuery) 在移动设备上调用函数,但 jQuery 动画不起作用

jquery - 如果窗口高度,则更改 css 高度

javascript - solr 正在为我的本地 iis 工作,而不是为托管 iis 工作

javascript - 使用对象列表中的循环将数据附加到组件

jquery - 命名 anchor 不适用于动态 html 和 jquery

Javascript 字符串替换没有效果

c# - .NET MVC 的 jQuery getJSON 不工作

javascript - Jquery - 无法在网页上显示 slider - 已编辑?