如何克隆或重新调度 DOM 事件? [英] How to clone or re-dispatch DOM events?
问题描述
我正在寻找一种简单而抽象的方法来克隆或重新调度 DOM 事件.我对克隆 DOM 节点不感兴趣.
I'm looking for a simple and abstract way of cloning or re-dispatching DOM events only. I am not interested in cloning DOM nodes.
我做了一些实验,阅读 DOM 事件规范 而我没有找到明确的答案.
I've experimented a bit, read the DOM Events specification and I found no clear answer.
理想情况下,我正在寻找以下内容:
Ideally, I'm looking for something as straight-forward as:
handler = function(e){
document.getElementById("decoy").dispatchEvent(e)
}
document.getElementById("source").addEventListener("click", handler)
这个代码示例当然行不通.有一个 DOM 异常表明当前正在调度事件 - 很明显.
This code example, of course, does not work. There's a DOM exception stating that the event is currently being dispatched - obviously.
我想避免使用 document.createEvent()
手动创建新事件、初始化它们并分派它们.
I'd like to avoid manually creating new events with document.createEvent()
, initializing them and dispatching them.
是否有针对此用例的简单解决方案?
Is there a simple solution to this use case?
推荐答案
我知道,这个问题很老了,OP 希望避免创建/初始化方法,但是有一种相对简单的方法来复制事件:
I know, the question is old, and the OP wanted to avoid creating / initializing approach, but there's a relatively straightforward way to duplicate events:
new_event = new MouseEvent(old_event.type, old_event)
如果你想要的不仅仅是鼠标事件,你可以这样做:
If you want more than just mouse events, you could do something like this:
new_event = new old_event.constructor(old_event.type, old_event)
在原始上下文中:
handler = function(e) {
new_e = new e.constructor(e.type, e);
document.getElementById("decoy").dispatchEvent(new_e);
}
document.getElementById("source").addEventListener("click", handler);
(对于 jQuery 用户:您可能需要使用 e.originalEvent.constructor
而不是 e.constructor
)
(For jQuery users: you may need to use e.originalEvent.constructor
instead of e.constructor
)
这篇关于如何克隆或重新调度 DOM 事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!