单击事件对动态生成的元素不起作用 [英] Click event doesn't work on dynamically generated elements

查看:31
本文介绍了单击事件对动态生成的元素不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<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 的新标签.我还定义了一个与 test 关联的点击事件.但该事件不起作用.

I was trying to generate a new tag with class name test in the <h2> by clicking the button. I also defined a click event associated with test. But the event doesn't work.

有人可以帮忙吗?

推荐答案

您正在使用的 click() 绑定称为直接"绑定,它只会将处理程序附加到 已经存在.它不会绑定到将来创建的元素.为此,您必须使用 on()<创建委托"绑定/strong>.

The click() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on().

委托事件的优点是它们可以处理来自稍后添加到文档的后代元素的事件.

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

来源

这是您要找的:

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+ 版本的用户.如果您使用的是旧版本,请参阅下面的上一个答案.

The above works for those using jQuery version 1.7+. If you're using an older version, refer to the previous answer below.

上一个答案:

尝试使用 live():

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


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

为我工作.尝试 jsFiddle.

Worked for me. Tried it with jsFiddle.

或者使用 delegate() 有一种新奇的方法::>

Or there's a new-fangled way of doing it with delegate():

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

更新的 jsFiddle.

这篇关于单击事件对动态生成的元素不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆