将 Click 事件侦听器添加到 TypeScript 中的 Button

在 TypeScript 中将 Click 事件侦听器添加到 Button

Add a Click event listener to a Button in TypeScript

在 TypeScript 中为按钮添加点击事件监听器:

  1. 选择按钮元素。
  2. 使用该addEventListener()方法为其添加点击事件侦听器。
  3. 每次单击按钮时,该方法都会调用一个函数。

以下是本文示例的 HTML。

索引.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> </head> <body> <button id="btn">Click</button> <script src="./src/index.ts"></script> </body> </html>

这是相关的 TypeScript 代码。

源代码/index.ts
const button = document.getElementById('btn'); button?.addEventListener('click', function handleClick(event) { console.log('button clicked'); console.log(event); console.log(event.target); });

我们使用
document.getElementById
方法来选择按钮元素。

The getElementById method returns null if no element with the provided id
was found in the DOM, so we had to use the
optional chaining (?.)
operator to short-circuit if the button variable stores a null value.

We called the
addEventListener
method on the button element.

The addEventListener method takes 2 arguments:

  1. The type of the event to listen for. If you need a list of all of the
    available event types, check out this
    MDN events list.

  2. A function to be invoked every time the event is triggered.

The function in the example gets invoked every time the button is clicked and logs a message to the console.

event参数是一个包含许多不同属性的对象例如,event.target指的是被点击的按钮。

您可以使用相同的方法为多个按钮添加点击事件侦听器。

源代码/index.ts
const buttons = Array.from(document.getElementsByClassName('btn')); buttons.forEach(btn => { btn.addEventListener('click', function handleClick(event) { console.log('button clicked'); console.log(event); console.log(event.target); }); });

我们使用该document.getElementsByClassName方法选择具有btn类的元素集合并将该集合转换为数组。

我们传递给forEach()方法的函数会为数组中的每个元素(按钮)调用,并为每个元素添加一个点击事件侦听器。