在我的应用程序中,我在同一页面上运行两次$(document).ready(
是否会在它们之间发生冲突?
在此先感谢,
院长可以运行2个document.ready使它们发生冲突吗?
2
A
回答
6
没有。 jQuery事件堆叠在一起,并将逐个执行。
从jQuery docs on bind():
当一个事件到达的元素,绑定到该事件类型的元件的所有处理程序被解雇。如果有多个处理程序注册,它们将始终按照它们绑定的顺序执行。
1
编号jQuery的目的是堆叠它们。
6
不会有冲突。
$(document).ready(function() { alert("One"); });
$(document).ready(function() { alert("Two"); });
将提醒两次。
4
$(document).ready()
非常安全 - 您可以挂钩多个处理程序或在事件已经被触发很长时间后使用它。
如果调试到jQuery的(只包括unminified版本),你会看到.ready()
样子:
ready: function(fn) {
// Attach the listeners
jQuery.bindReady();
// If the DOM is already ready
if (jQuery.isReady) {
// Execute the function immediately
fn.call(document, jQuery);
// Otherwise, remember the function for later
} else if (readyList) {
// Add the function to the wait list
readyList.push(fn);
}
return this;
}
所以,如果jQuery.isReady
(指示文件准备已经发生),那么$(文件).ready()函数被立即调用。否则,该函数将被添加到一个处理程序数组中。
内部jQuery的自己ready
处理程序:
// If there are functions bound, to execute
if (readyList) {
// Execute all of them
var fn, i = 0;
while ((fn = readyList[ i++ ])) {
fn.call(document, jQuery);
}
// Reset the list of functions
readyList = null;
}
因此,在ready
jQuery的遍历,并调用它注定要ready
的所有功能。这些函数被串行调用(一个接一个地,不是并行地)。这意味着一个人会在下一个开始之前完成。
+1,用于更好,更彻底的解释。 – 2010-07-10 16:08:33