使用 TypeScript 将复选框设置为选中/未选中

在 TypeScript 中将复选框设置为选中/未选中:

  1. 选择复选框元素。
  2. 使用类型断言将元素键入为 HTMLInputElement
  3. 使用元素的 checked 属性将复选框设置为选中或未选中。

这是本文中示例的 index.html 文件。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <input type="checkbox" name="subscribe" id="subscribe" />

    <script src="./src/index.ts"></script>
  </body>
</html>

这是相关的 TypeScript 代码。

const checkbox = document.getElementById(
  'subscribe',
) as HTMLInputElement | null;

if (checkbox != null) {
  // ✅ Set checkbox checked
  checkbox.checked = true;

  // ✅ Set checkbox unchecked
  // checkbox.checked = false;
}

我们使用类型断言将复选框变量键入为 HTMLInputElement 或 null

如果我们正在使用选项或选择元素,则可以使用 HTMLOptionElement 或 HTMLSelectElement 类型。

我们在类型中包含 null 的原因是,如果在 DOM 中找不到具有提供的 id 的元素,document.getElementById 方法将返回 null

我们确保复选框变量在访问其 checked 属性之前不存储空值。

一旦我们进入 if 块,TypeScript 就知道被检查变量的类型是 HTMLInputElement 而不是 HTMLInputElement | null

如果我们确定该元素将存在于 DOM 中,则可以在类型断言中从类型中省略 null。

现在我们可以访问元素上的 checked 属性,因为我们已经正确输入了它。 该属性可用于读取或设置复选框元素的选中状态。

如果我们需要取消选中该复选框,请将其 checked 属性设置为 false

const checkbox = document.getElementById(
  'subscribe',
) as HTMLInputElement | null;

if (checkbox != null) {
  // ✅ Set checkbox checked
  checkbox.checked = true;

  // 👇️ true
  console.log(checkbox.checked);

  // ✅ Set checkbox unchecked
  checkbox.checked = false;
}

在类型断言中包含 null 始终是最佳实践,因为如果没有找到具有提供的 id 的元素,getElementById 方法将返回 null