Javascript 打字稿:类型“HTMLElement”上不存在属性“src”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35542176/
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
Typescript: Property 'src' does not exist on type 'HTMLElement'
提问by Bj?rn Hjorth
I get a error from Typescript and I am not sure how to correct it. The code works fine when "compiled" but I can't correct the error. I have extracted the parts that involve the error from my code. I guess I have to predifine the src but not sure how.
我从 Typescript 收到一个错误,我不知道如何纠正它。代码在“编译”时工作正常,但我无法纠正错误。我已经从我的代码中提取了涉及错误的部分。我想我必须预定义 src 但不确定如何。
Error msg in Editor and on Gulp compile:
编辑器和 Gulp 编译中的错误消息:
"Property 'src' does not exist on type 'HTMLElement'.at line 53 col 17"
“属性 'src' 不存在于类型 'HTMLElement'.at line 53 col 17”
...
element:HTMLElement; /* Defining element */
'''
this.element = document.createElement('img'); /*creating a img*/
'''
This is the method I run to render the element, position, top and left all works with out giving a error.
这是我用来渲染元素、位置、顶部和左侧的方法,所有这些都可以正常工作而不会出错。
display() {
this.element.src = this.file; /*This is the line that gives the error*/
this.element.style.position = "absolute";
this.element.style.top = this.pointX.toString() + "px";
this.element.style.left = this.pointY.toString() + "px";
document.body.appendChild(this.element);
};
回答by Oded Breiner
Using casting:
使用铸造:
(<HTMLImageElement>document.querySelector(".company_logo")).src
回答by John Weisz
Because src
is not a property of the HTMLElement
type, but of HTMLImageElement
.
因为src
不是HTMLElement
类型的属性,而是HTMLImageElement
.
If you are certain you'll get an img element, you might want to declare your variable with the correct subtype:
如果你确定你会得到一个 img 元素,你可能想用正确的子类型声明你的变量:
element: HTMLImageElement; /* Defining element */
// ...
this.element = document.createElement('img'); /*creating a img*/
Also, you might want to have a look at what document.createElement
returns. It's the very same type if you specify "img"
as its argument.
此外,您可能想看看document.createElement
返回的内容。如果您将"img"
其指定为参数,则它是完全相同的类型。
回答by aruna harichandan
document.getElementById('img').setAttribute( 'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==' );
Set source through set attribute method.
通过设置属性方法设置源。
回答by kierandes
Using casting like @whereDatApp.com suggested worked for me. Using query selector like this:
使用像 @whereDatApp.com 这样的铸造建议对我有用。使用这样的查询选择器:
querySelector("img[name='menubanner']")
回答by SLaks
You need to declare it as HTMLImageElement
, which has an src
property.
您需要将其声明为HTMLImageElement
,它具有一个src
属性。