以下代码失败(在 javascript 控制台中,以及通过浏览器扩展注入(inject)脚本时)
document.createEvent('TestEvent')
Firebug 吐出:
[Exception... "Operation is not supported"
code: "9"
nsresult: "0x80530009 (NS_ERROR_DOM_NOT_SUPPORTED_ERR)"
location: "http://www.google.com
Line: 71"]
Chrome 给出了类似的错误信息。我做错了什么?
最佳答案
来自documentation :
type
is a string that represents the type of event to be created. Possible event types include "UIEvents", "MouseEvents", "MutationEvents", and "HTMLEvents".
所以你可能想要:
var e = document.createEvent('HTMLEvents');
e.initEvent('TestEvent', true, true);
参见 event.initEvent
.
更新:也许 document.createEvent('Event');
对于自定义事件甚至更好,但它是 DOM Level 3 的一部分,我不知道它得到了多少支持。
关于javascript - document.createEvent 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4645724/