鼠标悬停时的事件委托 [英] Event delegation on mouseover

查看:100
本文介绍了鼠标悬停时的事件委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建点击事件时,我会尽力将它们绑定一次 - 通常绑定到预期触发事件的所有节点共享的父级。但是,我很好奇,鼠标悬停事件的最佳做法是:当结果是鼠标悬停时事件的持续触发时,将事件绑定到父节点是否仍然有意义?什么是最有效的做法?

When creating click events, I do my best to bind them only once – generally to a parent shared by all the nodes expected to trigger the event. I'm curious, however, what the best practice is with mouseover events: Does it still make sense to bind an event to a parent when the result would be the constant firing of the event on mouseover? What's the most efficient practice?

推荐答案

为了对这个问题提供一些结论,我将解释/引用这个答案的一些相关注释:'应该全部jquery事件被绑定到$(文档)?',上面引用了@Faust:

In order to provide some closure to this question, I'm going to paraphrase/quote some relevant notes from this answer: 'Should all jquery events be bound to $(document)?', which was referenced above by @Faust:

事件委托不会总是让你的代码更快。除非你绑定到动态元素或大量元素,否则你应该将事件处理程序直接绑定到事件发生的对象,因为这通常会更有效。

Event delegation does not always make your code faster. Unless you're binding to dynamic elements or a ton of elements, you should bind event handlers directly to the objects where the event happens as this will generally be more efficient.

更具体地说,这里是需要或有利的事件委托时间:

More specifically, here are times when event delegation is required or advantageous:


  • 当你对象时捕获事件是动态创建/删除的,你仍然希望捕获事件而不必显式r每次创建一个新的事件处理程序时都会使用ebind事件处理程序。

  • 当你有很多对象都需要完全相同的事件处理程序(其中批量至少为数百个)时。在这种情况下,在设置时绑定一个委托事件处理程序而不是数百个或更多直接事件处理程序可能更有效。请注意,委派事件处理在运行时的效率始终低于直接事件处理程序。

  • 当您尝试捕获(在文档中的更高级别)任何事件发生时文档中的元素。

  • 当您的设计明确使用事件冒泡和stopPropagation()来解决页面中的某些问题或功能时。

  • When the objects you are capturing events on are dynamically created/removed and you still want to capture events on them without having to explicitly rebind event handlers every time you create a new one.
  • When you have lots of objects that all want the exact same event handler (where lots is at least hundreds). In this case, it may be more efficient at setup time to bind one delegated event handler rather than hundreds or more direct event handlers. Note, delegated event handling is always less efficient at run-time than direct event handlers.
  • When you're trying to capture (at a higher level in your document) events that occur on any element in the document.
  • When your design is explicitly using event bubbling and stopPropagation() to solve some problem or feature in your page.

@ jfriend00的原始答案

Original answer by @jfriend00

这篇关于鼠标悬停时的事件委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆