Nic*_*las 4 javascript typescript angular
我有一个输入字段,当用户单击某个按钮时,需要将其聚焦并完全选择其文本值(这样当用户键入时,他们会替换整个值)。
这是输入字段的标记:
<input type="text" id="descriptionField" class="form-control">
Run Code Online (Sandbox Code Playgroud)
...以及负责焦点/选择的功能:
public copy(): void {
document.getElementById("descriptionField").focus();
document.getElementById("descriptionField").select();
}
Run Code Online (Sandbox Code Playgroud)
.focus()工作正常,但.select()抛出错误:
TS2339: Property 'select' does not exist on type 'HTMLElement'.
Run Code Online (Sandbox Code Playgroud)
我尝试过寻找解决方案,但大多数都依赖于 jQuery。有没有办法通过本机实现或 TypeScript 来解决这个问题?
您可以将其“类型转换”HTMLElement为具有以下方法的类型select:
(document.getElementById("descriptionField") as HTMLInputElement).select();
Run Code Online (Sandbox Code Playgroud)
或者:
(<HTMLInputElement>document.getElementById("descriptionField")).select();
Run Code Online (Sandbox Code Playgroud)
这基本上告诉编译器“别担心,我知道这里需要什么类型。” ,在 TypeScript 中称为类型断言。
它不会影响运行时,只是让编译器放心,这样它就不会有任何可抱怨的了。
| 归档时间: |
|
| 查看次数: |
3307 次 |
| 最近记录: |