jQuery/JavaScript 如何处理绑定到同一元素的多个事件处理程序?事件以及后果是什么?
考虑以下代码:
$('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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
处理程序按其绑定顺序触发,每个
$('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).我认为它们是作为两个独立的事件来维护的。触发后,它们会按照绑定的顺序执行。
I think they are maintained as two separate events. When triggered, they get executed in the same order they were bound.