Insert tags that were not seen by jQuery
Let's say I have this code in my page:
<script language="javascript">
$(document).ready(function() {
$(".test").click(function() {
alert('Hello');
});
});
</script>
Why does the previous code not apply to elements with class "test" that I add later in the document, for example, for example:
$('body').append('<p class="test">Test</p>');
Because what happens is that when I click the previous tag <p>
, nothing happens.
Also, if I have this:
<div id="first">Edit me.<div id="second">Save me.</div></div>
Can I do what the text describes? those. controlling div content #first
without affecting #second
div content ?
Thank.
source to share
The problem is that .click()
it only applies a listener to the elements available in the DOM when the method is executed. Instead, you should take a look at .on()
.
With the help .on()
you can delegate the event, for example this:
$("body").on("click", ".test", function() {
alert('Hello');
});
Now any element (current and future) with a class test
available in your body will have a listener for click events.
source to share
Because at the time you attach your event handler, the object doesn't exist yet. You cannot subscribe to items that don't exist. You can use the Live method for this.
http://api.jquery.com/live/
They seem to be outdated (thanks to @Anthony Grist). Use On or delegate () instead.
http://api.jquery.com/delegate/
$('div').on('click', function()
{
//Do something
});
source to share