如何使用事件构造函数从字符串创建本机事件?
How to create native events from strings using event constructors?
用document.createEvent
代替API is being deprecated. It allowed for native browser event creation using using the string names of those events. The now recommended way is to use event constructors。
即createEvent("HtmlEvents")
现在变成了 new HtmlEvent()
.
是否可以通过使用字符串的事件构造函数来创建这些事件?即 new CustomEvent("HtmlEvents")
?
我想这对你有帮助
var event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { /* ... */ }, false);
// Dispatch the event.
elem.dispatchEvent(event);
用于创建自定义事件
var event = new CustomEvent('build', { detail: elem.dataset.time });
function eventHandler(e) {
console.log('The time is: ' + e.detail);
}
甚至事件构造函数也只是全局 window
对象上的键:
function createEvent(type, ...eventArgs) {
return new window[type](eventArgs);
}
// examples:
console.log(
createEvent("KeyboardEvent", "keyboard event name"),
createEvent("MouseEvent", "mouse event name"),
);
用document.createEvent
代替API is being deprecated. It allowed for native browser event creation using using the string names of those events. The now recommended way is to use event constructors。
即createEvent("HtmlEvents")
现在变成了 new HtmlEvent()
.
是否可以通过使用字符串的事件构造函数来创建这些事件?即 new CustomEvent("HtmlEvents")
?
我想这对你有帮助
var event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { /* ... */ }, false);
// Dispatch the event.
elem.dispatchEvent(event);
用于创建自定义事件
var event = new CustomEvent('build', { detail: elem.dataset.time });
function eventHandler(e) {
console.log('The time is: ' + e.detail);
}
甚至事件构造函数也只是全局 window
对象上的键:
function createEvent(type, ...eventArgs) {
return new window[type](eventArgs);
}
// examples:
console.log(
createEvent("KeyboardEvent", "keyboard event name"),
createEvent("MouseEvent", "mouse event name"),
);