开发者

jQuery access to element by ID after a .load() call [duplicate]

开发者 https://www.devze.com 2023-03-14 22:11 出处:网络
This question already has answers here: How to select an element loade开发者_如何学Pythond through the jQuery load() function?
This question already has answers here: How to select an element loade开发者_如何学Pythond through the jQuery load() function? (2 answers) Closed 6 years ago.
$(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()

0

精彩评论

暂无评论...
验证码 换一张
取 消