jquery - 单击事件不适用于动态生成的元素

标签 jquery events

<分区>

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">

        $(document).ready(function() {

            $("button").click(function() {
                $("h2").html("<p class='test'>click me</p>")
            });   

            $(".test").click(function(){
                alert();
            });
        });

    </script>
</head>
<body>
    <h2></h2>
    <button>generate new element</button>
</body>
</html>

我试图生成一个类名为 test 的新标签在<h2>通过点击按钮。我还定义了一个与 test 关联的点击事件.但是该事件不起作用。

有人能帮忙吗?

最佳答案

您正在使用的 click() 绑定(bind)称为“直接”绑定(bind),它只会将处理程序附加到已经存在 的元素。它不会绑定(bind)到将来创建的元素。为此,您必须使用 on() 创建一个“委托(delegate)”绑定(bind)。 .

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

Source

这是您要查找的内容:

var counter = 0;

$("button").click(function() {
    $("h2").append("<p class='test'>click me " + (++counter) + "</p>")
});

// With on():

$("h2").on("click", "p.test", function(){
    alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<h2></h2>
<button>generate new element</button>

以上内容适用于使用 jQuery 1.7+ 版本的用户。如果您使用的是旧版本,请参阅下面的先前答案。


上一个答案:

尝试使用 live() :

$("button").click(function(){
    $("h2").html("<p class='test'>click me</p>")
});   


$(".test").live('click', function(){
    alert('you clicked me!');
});

为我工作。 Tried it使用 jsFiddle。

或者有一种新方法可以用 delegate() 来实现:

$("h2").delegate("p", "click", function(){
    alert('you clicked me again!');
});

An updated jsFiddle .

关于jquery - 单击事件不适用于动态生成的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6658752/

相关文章:

javascript - 检测 Firefox 中链接的点击

javascript - 当我单击另一个按钮时无法停止按钮单击事件

flash - 删除在 Actionscript 3 中具有匿名函数的监听器

javascript - 如何在 JavaScript 事件 onmouseover 或 onmousemove 等时设置条件

javascript - 如何获取不同javascript文件中变量的值?

javascript - Bootstrap Modal和YouTube Player技巧

jquery - HTML & CSS 博主侧边菜单?

javascript - 如何更改 html div 而不影响 JQuery 中的内部 div

java - 如何能够使用 getConstructor() 中的 .class? - java

Jquery 根据 ID 选择标签