javascript document.createEvent 失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4645724/
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
document.createEvent fails
提问by shmichael
The following code fails (in javascript console, and also when injecting a script via browser extension)
以下代码失败(在 javascript 控制台中,以及通过浏览器扩展程序注入脚本时)
document.createEvent('TestEvent')
Firebug spits out:
萤火虫吐出:
[Exception... "Operation is not supported"
code: "9"
nsresult: "0x80530009 (NS_ERROR_DOM_NOT_SUPPORTED_ERR)"
location: "http://www.google.com
Line: 71"]
Chrome gives a similar error message. What am I doing wrong?
Chrome 给出了类似的错误消息。我究竟做错了什么?
回答by Felix Kling
From the documentation:
从文档:
typeis a string that represents the type of event to be created. Possible event types include "UIEvents", "MouseEvents", "MutationEvents", and "HTMLEvents".
type是一个字符串,表示要创建的事件类型。可能的事件类型包括“UIEvents”、“MouseEvents”、“MutationEvents”和“HTMLEvents”。
So you probably want:
所以你可能想要:
var e = document.createEvent('HTMLEvents');
e.initEvent('TestEvent', true, true);
See event.initEvent.
Update:Maybe document.createEvent('Event');is even better for custom events, but it is part of DOM Level 3 and I don't know how much supported it is.
更新:document.createEvent('Event');对于自定义事件来说也许更好,但它是 DOM Level 3 的一部分,我不知道它得到了多少支持。
回答by powtac
Use one of these event types: https://developer.mozilla.org/en/DOM/document.createEvent#Notes
使用以下事件类型之一:https: //developer.mozilla.org/en/DOM/document.createEvent#Notes
TestEventis not a supported event type. Better use "MouseEvents" or "HTMLEvents".
TestEvent不是受支持的事件类型。最好使用“ MouseEvents”或“ HTMLEvents”。
回答by Ivo Wetzel
There's simply no event type called TestEvent:
根本就没有名为 的事件类型TestEvent:
https://developer.mozilla.org/en/DOM/document.createEvent#section_4
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-DocumentEvent-createEvent
https://developer.mozilla.org/en/DOM/document.createEvent#section_4
http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-DocumentEvent-createEvent
Maybe you meant TextEvent?
也许你的意思是TextEvent?
PS: Next time do at least a bit of own research before using SO like you would use Google ;)
PS:下次在使用 SO 之前至少做一些自己的研究,就像你使用谷歌一样;)

