使用 TypeScript 将复选框设置为选中/未选中
Set a Checkbox to Checked/Unchecked using TypeScript
在 TypeScript 中将复选框设置为选中/未选中:
- 选择复选框元素。
HTMLInputElement
使用类型断言键入元素。- 使用元素的
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; }
我们使用类型断言将checkbox
变量类型化为HTMLInputElement
or null
。
如果您正在使用选项或选择元素,则可以使用
HTMLOptionElement
或HTMLSelectElement
类型。
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.
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
.
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
。
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
方法将返回
。null
id