【问题标题】:document.createEvent failsdocument.createEvent 失败
【发布时间】:2011-01-10 10:23:54
【问题描述】:

以下代码失败(在 javascript 控制台中,以及通过浏览器扩展注入脚本时)

document.createEvent('TestEvent')

萤火虫吐了出来:

[Exception... "Operation is not supported" 
 code: "9" 
 nsresult: "0x80530009 (NS_ERROR_DOM_NOT_SUPPORTED_ERR)" 
 location: "http://www.google.com 
 Line: 71"] 

Chrome 会给出类似的错误消息。我做错了什么?

【问题讨论】:

    标签: javascript javascript-events


    【解决方案1】:

    来自documentation

    type 是一个字符串,表示要创建的事件的类型。可能的事件类型包括“UIEvents”、“MouseEvents”、“MutationEvents”和“HTMLEvents”。

    所以你可能想要:

    var e = document.createEvent('HTMLEvents');
    e.initEvent('TestEvent', true, true);
    

    event.initEvent

    更新:也许document.createEvent('Event'); 更适合自定义事件,但它是 DOM Level 3 的一部分,我不知道它的支持程度。

    【讨论】:

      【解决方案2】:

      使用以下事件类型之一:https://developer.mozilla.org/en/DOM/document.createEvent#Notes

      TestEvent 不是受支持的事件类型。最好使用“MouseEvents”或“HTMLEvents”。

      【讨论】:

        【解决方案3】:

        根本没有称为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

        也许你的意思是TextEvent

        PS:下次在使用 SO 之前至少做一些自己的研究,就像你使用 Google 一样;)

        【讨论】:

        • 我正在尝试创建自定义 DOM 事件。我想我必须做更多的阅读。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-20
        • 2016-01-22
        • 1970-01-01
        • 2013-02-24
        • 2011-01-17
        相关资源
        最近更新 更多