且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

点击事件在动态生成的元素上不起作用

更新时间:2023-09-29 21:01:17

p>您正在使用的 click()绑定称为直接绑定,只会将处理程序附加到已经存在的元素。它将不会被绑定到将来创建的元素。要做到这一点,您必须使用 on() 强>


委托事件具有以下优点:他们可以在稍后时间处理添加到文档的后代元素中处理事件。

来源



以下是您要查找的内容:



  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());}) code> 

 < script src =https://ajax.googleapis。 com / ajax / libs / jquery / 1.8.3 / jquery.min.js>< / script>< h2>< / h2>< button>生成新元素< / button>  



上述适用于使用jQuery版本1.7+的用户。如果您使用的是较旧版本,请参阅以前的答案。




上一个答案



尝试使用 live()

  $(button)点击(function(){
$ (h2)。html(< p class ='test'>点击我< / p>)
});


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

为我工作试用它与jsFiddle。



或者有一种新的方式做它与 delegate()

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

更新jsFiddle


<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>

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.

Can anyone help?

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.

Source

Here's what you're looking for:

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>

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


Previous Answer:

Try using live():

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


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

Worked for me. Tried it with jsFiddle.

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

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

An updated jsFiddle.