开发者

jQuery - document.ready not firing when content loaded with AJAX

I have a simple custom tabbing module, that loads tabs with an AJAX request (via $(elem).load()). On each page that is loaded with AJAX I have some JavaScript. The first time the page loads (via direct input of URL, not AJAX), the javascript fires up perfectly. When I navigate away from the page via the AJAX tabs, the javascripts from the pages aren't loading anymore.

Is there any way I can force them to execute?

(The javascript that is not firing is placed in a $(documen开发者_开发百科t).ready() function if that helps)


You need to use callback of load() function:

$(elem).load('source.html', function() { 
    // here you need to perofrm something what you need
    ActionOnDocumentReady();
});

You can put all your actions in $(document).ready into some function (ex ActionOnDocumentReady()) and call it on load() callback.


the domeready event fires only when is initial dom is ready (like the name and the jquery-api suggest).

if you want to use jquerys load() and fire a function if that loading has been done, you'll have to use a callback-function (according to the api).

if you want to do the same thing on domready and load-events, the best way would be to define a new function for that:

function dostuff(){
  // do some stuff here
}

and fire this function in both cases:

$(function(){  // domready | shortcut for "$(document).ready()"
  dostuff();
})

$('#something').load('script.php', function() { // callback on load()
  dostuff();
});


Put your $(document).ready() code in a new method. Lets call it methodA. Now call this methodA from $(document).ready(). Secondly, call the same method after ajax request is successful. That should solve your problem.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜