创建和触发事件

本文演示如何创建和分派 DOM 事件。此类事件通常称为**合成事件**,与浏览器本身触发的事件相对。

创建自定义事件

可以使用 Event 构造函数创建事件,如下所示

js
const event = new Event("build");

// Listen for the event.
elem.addEventListener(
  "build",
  (e) => {
    /* … */
  },
  false,
);

// Dispatch the event.
elem.dispatchEvent(event);

以上代码示例使用了 EventTarget.dispatchEvent() 方法。

此构造函数在大多数现代浏览器中受支持。有关更详细的方法,请参阅下面的 旧式方法

添加自定义数据 – CustomEvent()

要向事件对象添加更多数据,可以使用 CustomEvent 接口,并使用**detail**属性传递自定义数据。例如,可以按如下方式创建事件

js
const event = new CustomEvent("build", { detail: elem.dataset.time });

然后,您可以在事件侦听器中访问这些附加数据

js
function eventHandler(e) {
  console.log(`The time is: ${e.detail}`);
}

旧式方法

创建事件的较旧方法使用受 Java 启发的 API。以下显示了一个使用 document.createEvent() 的示例

js
// Create the event.
const event = document.createEvent("Event");

// Define that the event name is 'build'.
event.initEvent("build", true, true);

// Listen for the event.
elem.addEventListener(
  "build",
  (e) => {
    // e.target matches elem
  },
  false,
);

// target can be any Element or other EventTarget.
elem.dispatchEvent(event);

事件冒泡

通常希望从子元素触发事件,并让祖先元素捕获它;可以选择性地携带数据

html
<form>
  <textarea></textarea>
</form>
js
const form = document.querySelector("form");
const textarea = document.querySelector("textarea");

// Create a new event, allow bubbling, and provide any data you want to pass to the "detail" property
const eventAwesome = new CustomEvent("awesome", {
  bubbles: true,
  detail: { text: () => textarea.value },
});

// The form element listens for the custom "awesome" event and then consoles the output of the passed text() method
form.addEventListener("awesome", (e) => console.log(e.detail.text()));

// As the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point
textarea.addEventListener("input", (e) => e.target.dispatchEvent(eventAwesome));

动态创建和分派事件

元素可以侦听尚未创建的事件

html
<form>
  <textarea></textarea>
</form>
js
const form = document.querySelector("form");
const textarea = document.querySelector("textarea");

form.addEventListener("awesome", (e) => console.log(e.detail.text()));

textarea.addEventListener("input", function () {
  // Create and dispatch/trigger an event on the fly
  // Note: Optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element
  this.dispatchEvent(
    new CustomEvent("awesome", {
      bubbles: true,
      detail: { text: () => textarea.value },
    }),
  );
});

触发内置事件

此示例演示了如何使用 DOM 方法模拟对复选框的点击(即以编程方式生成点击事件)。查看示例。

js
function simulateClick() {
  const event = new MouseEvent("click", {
    view: window,
    bubbles: true,
    cancelable: true,
  });
  const cb = document.getElementById("checkbox");
  const cancelled = !cb.dispatchEvent(event);

  if (cancelled) {
    // A handler called preventDefault.
    alert("cancelled");
  } else {
    // None of the handlers called preventDefault.
    alert("not cancelled");
  }
}

另请参阅