Newly added elements on page aware of previously defined Javascript code
In this very simplified and minimized example click event handler has been defined for every a tag (simple alert is displayed after link is clicked). Once you click the button, second link is added to the page.
But if you click this newly added link, event handler wan't be called. Any idea why? What should be added/changed so that newly added elements are aware of the scripts defined on the main page?
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$("document").ready(function() {
$("a").click(function() {
alert("link is clicked");
return false;
});
$("#btn").click(function() {
$("#second").html("<a href='#'>Second link</a>");
});
});
</script>
</head>
<body>
<div id="first">
<input id="btn" type="button" value="Get new content"/>
<a href="#">Original link</a>
</div>
<div id="second"/>
</body>
</html>
In this particular case, what should be done so that second link is aware of event handler defined in script section so that alert is being displayed after link is clicked?
What's your advice on resolving these kind of situations? How do you make newly added elements on the page be aware of previous开发者_如何学编程ly defined Javascript code?
Because you're binding to all the existing links on the page. Try:
$('a').live('click', function(){
alert('link is clicked');
return false;
});
jQuery's live
function actually attaches an event handler to document.body
and then checks to see if the event matches when it eventually bubbles up to body. So it will work for all current and future objects on the page.
Note that if these links are in a particular container, this code is more efficient:
$('#container').delegate('a', 'click', function(){
...
});
delegate
only checks events that bubble up to #container
, so jQuery doesn't check against every click anywhere on the page.
You need to replace .click(function())
with .delegate()
or (less preferentially) .live("click", function())
.
This is because click()
binds to existing elements, whereas .delegate()
will
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
Simplified, .delegate()
attaches a listener to a specified element, and when it received a bubbled DOM event will catch it and execute the necessary function on the target element.
精彩评论