简体   繁体   English

我可以在同一元素上附加捕获和气泡阶段事件处理程序吗?

[英]Can i attach capture and bubble phase event handler on the same element?

Can i attach capture and bubble phase event handler(could be different or same function) on the same element? 我可以在同一元素上附加捕获和气泡阶段事件处理程序(功能可以相同或不同)吗?

I tried it and it's working fine. 我试过了,它工作正常。

Is it permitted as per W3C? 根据W3C是否允许? I don't see any limitation or restriction mentioned in the DOM3 Event specification. 我没有看到DOM3事件规范中提到的任何限制或限制。

Could someone please clarify it? 有人可以澄清一下吗?

var divList = document.getElementsByTagName('div');
var eventHandler = function(event){
console.log(event.currentTarget);
}
for(var index=0; index < divList.length; index++){
divList[index].addEventListener('click',eventHandler,true);
divList[index].addEventListener('click',eventHandler,false);
}

Yes, binding events to both phases is allowed . 是的, 允许将事件绑定到两个阶段。 Here are a few instances where it is very useful: 这是一些非常有用的实例:

  • Programmatic filling of form fields 以编程方式填写表单域
  • Programmatic queueing of form submit events 表单提交事件的程序排队
  • Programmatic syncing of multiple select elements 以编程方式同步多个选择元素

Some events, such as focus, don't bubble but can be captured. 有些事件(例如焦点)不会冒泡,但可以捕获。 The inline handler on the target element triggers before capture handlers for the target element. 目标元素上的内联处理程序在目标元素的捕获处理程序之前触发。

Many newly specified events in the web platform (such as the media events) do not bubble, which is a problem for frameworks like Ember that rely on event delegation. Web平台中许多新指定的事件(例如媒体事件)不会冒泡,这对于依赖事件委托的Ember这样的框架来说是个问题。 However, the capture API, which was added in IE9, is invoked properly for all events, and does not require a normalization layer. 但是,已针对所有事件正确调用了IE9中添加的捕获API,并且不需要规范化层。 Not only would supporting the capture API allow us to drop the jQuery dependency, but it would allow us to properly handle these non-bubbling events. 支持捕获API不仅使我们能够删除jQuery依赖关系,而且还将使我们能够正确处理这些非冒泡事件。 This would allow you to use events like playing in your components without having to manually set up event listeners. 这将允许您使用事件,例如在组件中播放,而无需手动设置事件侦听器。

References 参考文献

Yes but it should be discouraged , you should handle logic to trigger other events/ call functions in the callback. 是的,但是不建议这样做 ,您应该处理逻辑以触发回调中的其他事件/调用函数。

It's rare to have a use case where an element requires more than one of the same event type. 很少有用例,其中一个元素需要多个同一事件类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM