Click event doesn't work on dynamically genera

2018-12-31 00:15发布

This question already has an answer here:

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

标签: jquery events
20条回答
萌妹纸的霸气范
2楼-- · 2018-12-31 00:23

You CAN add on click to dynamically created elements. Example below. Using a When to make sure its done. In my example, i'm grabbing a div with the class expand, adding a "click to see more" span, then using that span to hide/show the original div.

$.when($(".expand").before("<span class='clickActivate'>Click to see more</span>")).then(function(){
    $(".clickActivate").click(function(){
        $(this).next().toggle();
    })
});
查看更多
裙下三千臣
3楼-- · 2018-12-31 00:24

Best way to apply event on dynamically generated content by using delegation.

$(document).on("eventname","selector",function(){
    // code goes here
});

so your code is like this now

$(document).on("click",".test",function(){
    // code goes here
});
查看更多
像晚风撩人
4楼-- · 2018-12-31 00:24

Use 'on' as click gets bind to the elements already present.

For e.g

$('test').on('click',function(){
    alert('Test');
})

This will help.

查看更多
流年柔荑漫光年
5楼-- · 2018-12-31 00:25

.live function works great.

It is for Dynamically added elements to the stage.

$('#selectAllAssetTypes').live('click', function(event){
                    alert("BUTTON CLICKED");
                    $('.assetTypeCheckBox').attr('checked', true);
                });

Cheers, Ankit.

查看更多
怪性笑人.
6楼-- · 2018-12-31 00:26

Reason:

In jQuery, Click()- attaches the event handler only if the element already exist in the html code.

It won't consider the new element which is created dynamically(Future element) after the page loaded.

Dynamic elements are created with the help of javascript or jquery(not in html).

So the click event doesn't fire.

Solution :

To overcome this we should use on() function.

delegate(),live() and on() functions have the advantages over the DOM elements.

on can trigger both existing elements as well as future elements.

on can consider the elements which are all present in the whole page.

delegate(),live() functions are deprecated(Don't use these).

You should use on function to trigger the event on dynamically created (future) elements.

Remove the code from $(document).ready:

$(".test").click(function(){

  alert();

});

Change into:

$(document).on('click','.test',function(){

  alert('Clicked');

});
查看更多
公子世无双
7楼-- · 2018-12-31 00:27

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.

查看更多
登录 后发表回答