CustomEvent() 构造函数创建新 CustomEvent .

注意: 此特征可用于 Web 工作者 .

句法

 event = new CustomEvent(typeArg, customEventInit);
					

参数

typeArg
DOMString 表示事件的名称。
customEventInit 可选
A CustomEventInit 字典,拥有以下字段:
  • "detail" , optional and defaulting to null , of type any, that is an event-dependent value associated with the event.

CustomEventInit 字典还接受字段来自 EventInit 字典。

返回值

新的 CustomEvent object of the specified type, with any other properties configured according to the CustomEventInit dictionary (if one was provided).

范例

// add an appropriate event listener
obj.addEventListener("cat", function(e) { process(e.detail) });
// create and dispatch the event
var event = new CustomEvent("cat", {
  detail: {
    hazcheeseburger: true
  }
});
obj.dispatchEvent(event);
					

Additional examples can be found at 创建和触发事件 .

规范

规范 状态 注释
DOM
The definition of 'CustomEvent()' in that specification.
实时标准 初始定义。

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
CustomEvent() 构造函数 Chrome 15 Edge ≤18 Firefox 11 IE No Opera 11.6 Safari 6.1 WebView Android ≤37 Chrome Android 18 Firefox Android 14 Opera Android 12 Safari iOS 6.1 Samsung Internet Android 1.0

图例

完整支持

完整支持

不支持

不支持

Polyfill

You can polyfill the CustomEvent() constructor functionality in Internet Explorer 9 and higher with the following code:

(function () {
  if ( typeof window.CustomEvent === "function" ) return false;
  function CustomEvent ( event, params ) {
    params = params || { bubbles: false, cancelable: false, detail: null };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
   }
  window.CustomEvent = CustomEvent;
})();
					

Internet Explorer >= 9 adds a CustomEvent object to the window, but with correct implementations, this is a function.

另请参阅

元数据

  • 最后修改: