开发者

Which jQuery-attached event on my element fires first?

Suppose I have a button on my web page:

<input type='button' id='myButton' value='Click me!' />

Suppose that I write the following jQuery:

开发者_开发百科$(document).ready(function() {
    var button = $('#myButton');
    button.click(doThis);
    button.click(doThat);
}

function doThis() {
    // do something
}

function doThat() {
    //do something else
}

When the button is clicked, how can I know which function should execute first? Or does it depend on things beyond my control?


The handlers are executed in the order they have been attached to the element (see the documentation):

If there are multiple handlers registered, they will always execute in the order in which they were bound.

So in your case, first doThis and then doThat will be executed.

Note: This only applies to jQuery. For information about pure DOM event handlers, see @StuperUser's answer.

For general information about event handling in JavaScript, I can recommend the articles at quirksmode.org.


jQuery events will fire in order of attachment as @Felix Kling and @Kyle have said.

This is not the case outside of jQuery. According to jQuery in Action Second Edition - on the DOM Level 2 event model (e.g. using addEventListener rather than $.bind or methods that call it)

Note that even though the handlers fire in the order they were established, this order isn't guaranteed by the standard! Testers of this code never observed an order other than the order of establishment, but it would be foolish to write code that relies on this order. Always be aware that multiple handlers established on an element may fire in random order.

Yet another reason to use jQuery.


They will execute in the order you bind them (doThis followed by doThat).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜