This question already has an answer here:
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:
<a class="myclass" href="#">test1</a>
<a class="myclass" href="#">test2</a>
<a class="myclass" href="#">test3</a>
That works with no problem. However, consider if the "myclass" elements were written to the page at some future time.
For example:
<a id="anchor1" href="#">create link dynamically</a>
<script type="text/javascript">
$(function(){
$("#anchor1").click( function() {
$("#anchor1").append('<a class="myclass" href="#">test4</a>');
});
});
</script>
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".
Any idea how I can fix this?
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.
After jQuery 1.7 the preferred methods are .on() and .off()
Sean's answer shows an example.
Now Deprecated:
Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
link text