开发者

How to run DOM ready functions in jQuery when they have been loaded via AJAX?

My company has a web application built in ASP.NET and they have asked me to code up a widget for a dashboard page they already have. These widgets are custom user controls that are loaded dynamically at runtime. My problem is that I have some custom javascript that needs to run every time the widget is loaded.

$(function ()
{
    // Setup widget.
});

This works great when the dashboard page first loads.开发者_如何学编程 My DOM ready function runs and all is well. However, whenever a user moves around widgets on their dashboard all the widgets are in an update panel and they all reload using AJAX. DOM ready functions do not run when they are inserted into the page via AJAX.

Any suggestions for how to ensure this code runs every time the widget is loaded?


The way I get around this is to name the given event bidings when you define them initially on load. Then, in the callback function to the ajax unset these events, and set them all up again for the newly created dom elements.


Can you not use the ASP.Net AJax pageLoad() function?

Explanation of how it differs to $(document).Ready() here -> http://encosia.com/document-ready-and-pageload-are-not-the-same/


You could have each widget call the setup function after its HTML is written into the DOM.


When you do your ajax call have return function execute your setup code

$.post(url, {/*data*/}, function() {
    // return function call
    // do setup code
});

EDIT:

Since you dont have control you could have a handler to intercept ajax calls:

$(#your-widget-area).ajaxComplete(function(e, xhr, settings) {

});

you can find the documentation here : http://api.jquery.com/ajaxComplete/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜