How to fire event handlers after AJAX content has loaded in JQuery

半世苍凉 提交于 2020-01-15 12:44:45

问题


I'm trying to use an AJAX request to load some information into a table using JQuery. I can load the content easily but I am having problems adding event handlers to apply style on the loaded content.

I am applying a striping widget to the table. However when my AJAX request comes back and my information is appended to the table body it does not have the style applied.

The JQuery tutorial mentions using the load event to handle this, but I can't get it to work.

Any help would be appreciated.

$(document).ready(function(){
    $("#cowTable").tablesorter();
    addTableStriping();
});

function addTableStriping(){
    $("#cowTable").tablesorter({
        // striping looking
        widgets: ['zebra']  
    });
};

$(function(){
    $("#loadCowsButton").click(function(){
        $.post("loadCows.php", "scottm", function(xml) {
            $("#cowTable tbody").append(xml);
        });
    });
});


回答1:


I've found a solution for this. You need to trigger "applyWidgets" after updating. Thanks for all the help from everyone, I wouldn't have found this out without your help.

$(function(){
    $("#loadCowsButton").click(function(){
        $.post("loadCows.php", "scottm", function(xml) {
            $("#cowTable").append(xml);
            $("#cowTable").trigger("update");
            $("#cowTable").trigger("applyWidgets")
        });
    });
});



回答2:


You might want to try the Livequery Plugin

Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.




回答3:


THIS is what you should do:

Found it on the tablesorter website.

The long and short of it is that you should call $( "#cowTable" ).trigger( "update" ); after appending the data.




回答4:


Why not just call it in the AJAX callback?

$(function(){
    $("#loadCowsButton").click(function(){
        $.post("loadCows.php", "scottm", function(xml) {
            $("#cowTable tbody").append(xml);
            addTableStriping(); // <-- here
        });
    });
});



回答5:


this should do it ..

$(function(){
    $("#loadCowsButton").click(function(){
        $.post("loadCows.php", "scottm", function(xml) {
            $("#cowTable tbody").append(xml);
            $("#cowTable").trigger( "update" );
        });
    });
});


来源:https://stackoverflow.com/questions/2124235/how-to-fire-event-handlers-after-ajax-content-has-loaded-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!