我的元素上的哪个 jQuery 附加事件首先触发?

发布于 2024-11-28 17:09:52 字数 414 浏览 1 评论 0原文

假设我的网页上有一个按钮:

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

假设我编写了以下 jQuery:

$(document).ready(function() {
    var button = $('#myButton');
    button.click(doThis);
    button.click(doThat);
}

function doThis() {
    // do something
}

function doThat() {
    //do something else
}

单击该按钮时,我如何知道应该首先执行哪个函数?或者这取决于我无法控制的事情?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

无畏 2024-12-05 17:09:52

处理程序按照附加到元素的顺序执行(请参阅文档):

如果注册了多个处理程序,它们将始终按照绑定的顺序执行。

因此,在您的情况下,首先执行 doThis ,然后执行 doThat

注意:这仅适用于 jQuery。有关纯 DOM 事件处理程序的信息,请参阅 @ StuperUser的回答

有关 JavaScript 中事件处理的一般信息,我可以推荐quirksmode.org 上的文章

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.

烟凡古楼 2024-12-05 17:09:52

正如 @Felix Kling 和 @Kyle 所说,jQuery 事件将按照附件的顺序触发。

在 jQuery 之外,情况并非如此。根据 jQuery in Action Second Edition - 在 DOM Level 2 事件模型上(例如使用 addEventListener 而不是 < code>$.bind 或调用它的方法)

请注意,即使处理程序按照它们建立的顺序触发,标准并不能保证这个顺序!此代码的测试人员从未观察到除建立顺序之外的顺序,但是编写依赖于这个顺序的代码是愚蠢的。请始终注意,在一个元素上建立的多个处理程序可能会以随机顺序触发。

使用 jQuery 的另一个原因。

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.

伴梦长久 2024-12-05 17:09:52

它们将按照您绑定它们的顺序执行(doThis 后 doThat)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文