在 TypeScript 中将 Click 事件侦听器添加到 Button
Add a Click event listener to a Button in TypeScript
在 TypeScript 中为按钮添加点击事件监听器:
- 选择按钮元素。
- 使用该
addEventListener()
方法为其添加点击事件侦听器。 - 每次单击按钮时,该方法都会调用一个函数。
以下是本文示例的 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 代码。
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:
-
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. -
A function to be invoked every time the event is triggered.
event
参数是一个包含许多不同属性的对象。例如,event.target
指的是被点击的按钮。
您可以使用相同的方法为多个按钮添加点击事件侦听器。
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()
方法的函数会为数组中的每个元素(按钮)调用,并为每个元素添加一个点击事件侦听器。