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

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

Set a Checkbox to Checked/Unchecked using TypeScript

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

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

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

索引.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 代码。

源代码/index.ts
const checkbox = document.getElementById( 'subscribe', ) as HTMLInputElement | null; if (checkbox != null) { // ✅ Set checkbox checked checkbox.checked = true; // ✅ Set checkbox unchecked // checkbox.checked = false; }

我们使用类型断言将checkbox变量类型化为HTMLInputElement
or
null

如果您正在使用选项或选择元素,则可以使用
HTMLOptionElementHTMLSelectElement类型。

The reason we included null in the type is because the
document.getElementById
method will return null if no element with the provided id is found in the
DOM.

We make sure that the checkbox variable does not store a null value before accessing its checked property.

Once we enter the if block, TypeScript knows that the type of the checked
variable is HTMLInputElement and not HTMLInputElement | null.

If you are certain that the element will exist in the DOM, you can omit null from the type in the type assertion.

Now we are able to access the checked property on the element, because we’ve
typed it correctly. The property can be used to read or set the checked state of
the checkbox element.

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

源代码/index.ts
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包含在类型断言中
始终是最佳实践,因为如果找不到提供的元素,该
getElementById方法将返回
nullid