jQuery access to element by ID after a .load() call [duplicate]
$(document).ready(function() {
$("img.tile").click(function() {
var actid = $(this).data().id;
$("#lz").load("/dialog/pre?actid=" + actid);
$("#btnCheck").click(function() {
alert("test");
});
});
The load()
call brings in an HTML fragment that has an <input id="btnCheck" value="Check" />
But the event doesn't fire when I click on it.
Must have something to do with how the fragment is loaded. How do you make this work?
Correct, you either need to attached the click
event after you are sure the data has loaded or use the live
event to attach it. live
will attach a handler if it finds it now or at any point in the future and is probably easiest to implement:
$("#btnCheck").live('click', function() {
alert("test");
});
Alternatively, you can attach it after you are sure the data has loaded. As @bzlm pointed out in his comment load
is an asynchronous event so you can't assume it has finished in any subsequent code. Fortunately load
allows you to pass a function as a second argument that will fire after all of the data has loaded:
$("#lz").load("/dialog/pre?actid=" + actid, function() {
$("#btnCheck").click(function() {
alert("test");
});
});
The best way would be to use delegate
and take advantage of event bubbling to capture events on elements that may not yet exist. This is very easy, especially as you can work on the existing selection to provide a context:
$(document).ready(function () {
$("img.tile").click(function () {
var actid = $(this).data().id;
$("#lz")
.load("/dialog/pre?actid=" + actid)
.delegate("#btnCheck", "click", function () {
alert("test");
});
});
});
This is functionally equivalent to the load
examples, but will have slightly better performance in several ways.
Try:
$(document).ready(function() {
$("img.tile").click(function() {
var actid = $(this).data().id;
$("#lz").load("/dialog/pre?actid=" + actid);
$("#btnCheck").live('click', function() {
alert("test");
}); });
This will pick up any elements added to the dom after the load event. A better way might be to use .delegate()
精彩评论