Sunday, June 23, 2019

jquery - Click event doesn't work on dynamically generated elements

















I was trying to generate a new tag with class name test in the

by clicking the button. I also defined a click event associated with test. But the event doesn't work.



Can anyone help?



Answer



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

click me " + (++counter) + "

")
});

// With on():


$("h2").on("click", "p.test", function(){
alert($(this).text());
});









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

click me

")
});


$(".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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...