typescript 使用打字稿,如何更新 HTML 元素的值和文本。?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39879672/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using typescript, how to update HTML element's value and text.?
提问by Raj Bhatia
I want to update update certain attributes of html element using typescript. Is it possible, if Yes then how..? I'm providing my code.
我想使用打字稿更新 html 元素的某些属性。是否有可能,如果是,那么如何..?我正在提供我的代码。
HTML:-
HTML:-
<a ref="#" id="userProfileName" style="padding-top: 0px; padding-bottom: 0px; padding-right: 10px; padding-left: 10px;">
<img src="" alt="" id="userProfilePic" class="profile-img" style="width: 56px; height: 50px;"></a>
Typescript:-
打字稿:-
document.getElementById('userProfilePic').src = profile.picture;
document.getElementById('userProfileName').textContent = profile.given_name;
Error I'm getting:-
我得到的错误:-
error TS2339: Property 'src' does not exist on type 'HTMLElement'.
回答by Nitzan Tomer
The document.getElementByIdfunction returns an element of type HTMLElementwhich does not have the src
property.
You need to type assert it to HTMLImageElement:
所述的document.getElementById函数返回类型的元素的HTMLElement不具有的src
特性。
你需要输入 assert 到HTMLImageElement:
(document.getElementById('userProfilePic') as HTMLImageElement).src = profile.picture;
The same goes for the HTMLAnchorElementbut textContent
can be accessed straight from the HTMLElement
so no need to cast.
HTMLAnchorElement也是如此,但textContent
可以直接从 访问,HTMLElement
因此无需强制转换。