Saturday, 24 September 2016

javascript - How do I attach events to dynamic HTML elements with jQuery?




Suppose I have some jQuery code that attaches an event handler to all elements with class .myclass.




For example:



$(function(){
$(".myclass").click( function() {
// do something
});
});


And my HTML might be as follows:




test1
test2
test3


That works with no problem.
However, consider if the .myclass elements were written to the page at some future time.



For example:




create link dynamically




In this case, the test4 link is created when a user clicks on a#anchor1.



The test4 link does not have the click() handler associated with it, even though it has class="myclass".



Basically, I would like to write the click() handler once and have it apply to both content present at page load, and content brought in later via AJAX / DHTML. Any idea how I can fix this?


Answer



I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.



From http://api.jquery.com/live/





As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().




For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.



See http://api.jquery.com/on/



So instead of...




$(".myclass").click( function() {
// do something
});


You can write...



$('body').on('click', 'a.myclass', function() {
// do something

});


This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.



The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:



$('ul').on('click', 'li', function() {
alert( $(this).text() );
});



As long as the ul tag exists this will work (no li elements need exist yet).


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...