jQuery/JavaScript 如何处理绑定到同一元素的多个事件处理程序?事件以及后果是什么?

发布于 2025-01-06 05:26:32 字数 616 浏览 1 评论 0原文

考虑以下代码:

$('div').click(function(){
    $(this).animate({height:100}, 500)
    $(this).css({opacity:1});
});

对比:

$('div').click(function(){
    $(this).animate({height:100}, 500);
})
.click(function(){
    $(this).css({opacity:1});
});

jQuery 或 JavaScript 是否本质上将第二个代码示例“编译”为类似于第一个的代码,而不是维护两个单独的事件处理程序?我询问 jQuery 或 JavaScript 是否会执行此操作,因为我也有兴趣知道这种“编译”是否是本机 JS 的功能或由 jQuery 实现的功能。

在我看来,这个“编译”实际上并没有完成,至少没有以消除两个代码示例之间的差异的方式完成。使用 JSPerf,我比较了每个代码之间的速度,看来第一个代码示例要快得多。

Consider the following code:

$('div').click(function(){
    $(this).animate({height:100}, 500)
    $(this).css({opacity:1});
});

Versus:

$('div').click(function(){
    $(this).animate({height:100}, 500);
})
.click(function(){
    $(this).css({opacity:1});
});

Does jQuery or JavaScript essentially "compile" the second code sample into something like the first rather than maintaining two separate event handlers? I ask about whether jQuery or JavaScript does this because I'd also be interested to know if such "compilation" is a feature of native JS or something implemented by jQuery.

It seems to me that this "compilation" is not actually done, at least not in a way that eliminates the differences between the two code samples. Using JSPerf, I compared the speed between each one and it appears that the first code sample is substantially faster.

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

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

发布评论

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

评论(2

笑咖 2025-01-13 05:26:32

处理程序按其绑定顺序触发,每个 $('div').click() 将另一个处理程序绑定到相关元素。在您的情况下,第一个仅绑定 1 个事件处理程序,因此执行速度更快,因为它只触发一个事件。第二个绑定两个事件处理程序,因此速度较慢,因为它触发两个事件而不是一个(更多开销)。

Handlers are fired in the order they are bound and each $('div').click() binds another handler to the element in question. In your case the first one only binds 1 event handler and thus performs faster because it only fires one event. The second binds two event handlers, and thus is slower because it fires two events instead of one (more overhead).

不及他 2025-01-13 05:26:32

我认为它们是作为两个独立的事件来维护的。触发后,它们会按照绑定的顺序执行。

I think they are maintained as two separate events. When triggered, they get executed in the same order they were bound.

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