最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Can we alter image source from typescript code? - Stack Overflow

programmeradmin5浏览0评论

I am starting with simple Typescript(.ts)+HTML(.js) code for practice. In HTML page I have below tag to display certain image :

<img id="myimage" src='images/samsung_edge_silver.jpg' height="250px">
<div><b><span id="Name"></b></div>

I am starting with simple Typescript(.ts)+HTML(.js) code for practice. In HTML page I have below tag to display certain image :

<img id="myimage" src='images/samsung_edge_silver.jpg' height="250px">
<div><b><span id="Name"></b></div>

Now I have ts file to alter fields in this code. I can change the value of span field Name using :

document.getElementById("pName").innerHTML = productName;

But is there any way I can alter the value of source URL for myimage.

I read a few answers, people are giving an answer for angular mostly. But this is pure typescript+html. How do we assign a new value to image source?

Share Improve this question edited Jul 19, 2019 at 8:25 Nazim Kerimbekov 4,7839 gold badges36 silver badges58 bronze badges asked Jul 19, 2019 at 8:24 Vishnu DahatondeVishnu Dahatonde 1893 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

You have to do this:

(document.getElementById('test') as HTMLImageElement).src = 'http://www.image.';

The reason for this is that document.getElementById('id') will return an HTMlElement and not all HTMLElement have src property.

You can set it like this.

document.getElementById('myimage').src = 'http://yourImagePathHere';

Checkout the fiddle here

If you are using angular, you can do something like this:

HTML:

<img [src]="mySource">

Typescript:

mySource = "/maybeAssets/default.png";

changeSourceImage() {
   this.mySource = "/maybeAssets/funnyCats.png"
}
发布评论

评论列表(0)

  1. 暂无评论