2

Guy's i am bit confused about the following code, in bellow code has two function then which will execute first Function1() or Function2 () ?

$(document).ready(function() {
  // some code here for function1()
});
$(document).ready(function() {
  // other code here for function2()
});
4

4 回答 4

3

函数 1 将首先执行。jQuery 将始终按照它们绑定的顺序执行事件处理程序(请记住,委托处理程序将在直接处理程序之后执行,因为它们仅在事件通过 DOM 冒泡时发生——但这并不适用于此)。

这记录在on方法文档的括号中:

(绑定到元素的事件处理程序的调用顺序与它们绑定的顺序相同。)

于 2013-07-05T11:28:19.037 回答
1

Both will be executed. You are registering events to trigger when document is ready. You can register more than one event for a given object, even if it's triggered by the same action.

Normally, I would expect the code that is declared first to trigger first, but I wouldn't write code that has dependencies in different blocks as it will be failure prone.

I would assume such a scenario in component based frameworks (like Wicket), where each component can have it's ready block, but if they are independant from each other, you wouldn't have to care about which one executes first.

If you have code where the execution order is an issue, I would recommend searching for some other approach to avoid this. As other answers have already stated, you can expect one order, but I wouldn't trust in all browser implementations, and worse than that, in future implementations.

So, as a general rule: keep things simple, if you need more than one event for one object it's fine as long as they're not dependant, else put them in the same block.

于 2013-07-05T11:32:29.580 回答
0

第一个 document.ready 将首先执行。

于 2013-07-05T11:29:24.873 回答
0

第一个函数 1 将首先执行,因为 jQuery 总是在编写处理程序时执行它们

您可以拥有任意数量的它们,它们将按照$()or$(document).ready()函数的执行顺序执行。(即每个处理程序都添加到队列中)

于 2013-07-05T11:29:40.920 回答