Javascript dispatchEvent 在 IE11 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27176983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:49:12  来源:igfitidea点击:

dispatchEvent not working in IE11

javascriptjavascript-eventsinternet-explorer-11dispatchevent

提问by Kohei Mikami

I am using the following code to submit to a form:

我正在使用以下代码提交表单:

element.dispatchEvent(new Event("submit"));

Inspector returns the error: Object doesn't support this action

检查器返回错误:对象不支持此操作

This works in Chrome.

这适用于 Chrome。

The purpose of this command is to make a division call the submit event on a form when clicked.

这个命令的目的是让一个部门在点击表单时调用提交事件。

Jquery is not an option

Jquery 不是一个选项

回答by Kohei Mikami

This is the best way to make it work for IE11 and other browsers with considering future changes.

考虑到未来的变化,这是使其适用于 IE11 和其他浏览器的最佳方式。

var event;
if(typeof(Event) === 'function') {
    event = new Event('submit');
}else{
    event = document.createEvent('Event');
    event.initEvent('submit', true, true);
}

$el.dispatchEvent(event);

回答by Taimo Kolsar

I just had the same problem, but the following seems to work in IE11:

我刚刚遇到了同样的问题,但以下内容似乎在 IE11 中有效:

var event = document.createEvent("Event");
event.initEvent("submit", false, true); 
// args: string type, boolean bubbles, boolean cancelable
element.dispatchEvent(event);

回答by Sanath

It's best to use a polyfil to fix this. (custom-event-polyfill)

最好使用 polyfil 来解决这个问题。(自定义事件polyfill)

# using yarn 
$ yarn add custom-event-polyfill

# using npm 
$ npm install --save custom-event-polyfill

then include/require it in your javascript

然后在你的javascript中包含/要求它

import 'custom-event-polyfill';

import 'custom-event-polyfill';

https://www.npmjs.com/package/custom-event-polyfill

https://www.npmjs.com/package/custom-event-polyfill

回答by Mike Wheaton

I assembled bits and pieces of various approaches and got this to work:

我组装了各种方法的点点滴滴,并使其发挥作用:

var customEvent = document.createEvent('HTMLEvents');
customEvent.initEvent('myCustomEvent', true, true);
document.dispatchEvent(customEvent);

To be honest, this doesn't make a lot of sense to me. It creates an event (naming it HTMLEventsseems to be required) on the document, then goes and initializes that event with another name. If anyone can explain this better please add a comment below so it can be incorporated into the answer.

老实说,这对我来说没有多大意义。它HTMLEvents在文档上创建一个事件(命名它似乎是必需的),然后使用另一个名称初始化该事件。如果有人可以更好地解释这一点,请在下面添加评论,以便将其纳入答案。

In any case, I'm able to listen to this custom event in IE11 (and modern browsers) with a standard event listener:

在任何情况下,我都可以使用标准事件侦听器在 IE11(和现代浏览器)中侦听此自定义事件:

document.addEventListener('myCustomEvent', function(){
  console.log('Event received.');
});