CustomEvent:CustomEvent() 建構子

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

備註: 此功能可在 Web Worker 中使用。

CustomEvent() 建構子用於建立新的 CustomEvent 物件。

語法

js
new CustomEvent(type)
new CustomEvent(type, options)

參數

type

一個字串,用於提供事件名稱。事件名稱區分大小寫。

options 選擇性

一個物件,除了 Event() 定義的屬性之外,還可以包含以下屬性:

detail 選擇性

一個與事件相關的值。可以透過事件處理器中的 CustomEvent.detail 屬性來存取此值。預設為 null

回傳值

一個新的 CustomEvent 物件。

範例

js
// 建立自訂事件
const catFound = new CustomEvent("animalfound", {
  detail: {
    name: "cat",
  },
});
const dogFound = new CustomEvent("animalfound", {
  detail: {
    name: "dog",
  },
});

const element = document.createElement("div"); // 建立一個 <div> 元素

// 新增事件監聽器
element.addEventListener("animalfound", (e) => console.log(e.detail.name));

// 觸發事件
element.dispatchEvent(catFound);
element.dispatchEvent(dogFound);

// 控制台會輸出「cat」和「dog」

更多範例請參見建立與觸發事件

規範

Specification
DOM
# ref-for-dom-customevent-customevent

瀏覽器相容性

參見