javascript jQuery - 使用 AJAX 加载内容时,document.ready 不会触发
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7498220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - document.ready not firing when content loaded with AJAX
提问by Eduard Luca
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.
我有一个简单的自定义选项卡模块,它使用 AJAX 请求(通过$(elem).load()
)加载选项卡。在每个加载了 AJAX 的页面上,我都有一些 JavaScript。页面第一次加载时(通过直接输入 URL,而不是 AJAX),javascript 完美启动。当我通过 AJAX 选项卡离开页面时,页面中的 javascript 不再加载。
Is there any way I can force them to execute?
有什么办法可以强迫他们执行吗?
(The javascript that is not firing is placed in a $(document).ready()
function if that helps)
($(document).ready()
如果有帮助,未触发的 javascript 被放置在一个函数中)
回答by Samich
You need to use callback of load()
function:
您需要使用load()
函数回调:
$(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.
您可以将所有操作$(document).ready
放入某个函数(ex ActionOnDocumentReady()
)中并在load()
回调中调用它。
回答by oezi
the domeready event fires only when is initial dom is ready (like the name and the jquery-apisuggest).
仅当初始 dom 准备好(如名称和jquery-api建议)时,domeready 事件才会触发。
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).
如果要使用 jquerys load() 并在加载完成后触发函数,则必须使用回调函数(根据 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:
如果你想对 domready 和 load-events 做同样的事情,最好的方法是为此定义一个新函数:
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();
});
回答by wasimbhalli
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.
将您的$(document).ready()
代码放在一个新方法中。让我们称之为methodA
。现在methodA
从$(document).ready()
. 其次,ajax请求成功后调用同样的方法。那应该可以解决您的问题。