最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Which jQuery-attached event on my element fires first? - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question asked Aug 9, 2011 at 16:14 Vivian RiverVivian River 32.5k64 gold badges210 silver badges324 bronze badges 1
  • They almost certainly will be called in the order in which the registrations were made, but that seems like a scary thing to rely on. – Pointy Commented Aug 9, 2011 at 16:30
Add a ment  | 

3 Answers 3

Reset to default 9

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 remend the articles at quirksmode.

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)

  1. 暂无评论