javascript 动态分配 img' src

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22568665/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:22:51  来源:igfitidea点击:

Assign img' src dynamically

javascripthtml

提问by EmilyJ

The page will display an image's url text correctly. But I am not sure how to assign the message to the img 's src to display the image.

该页面将正确显示图像的 url 文本。但我不确定如何将消息分配给 img 的 src 以显示图像。

<DIV class="msgStyle1" id="message">Waiting for image</DIV>
<div class="imgStyle1" id="message">
    <img src=whatneedtogohere /></div>


  function displayText(text) {
    console.log(text);
    document.getElementById("message").innerHTML=text;
    window.castReceiverManager.setApplicationState(text);
  };

回答by Shomz

Fixed HTML (switched classes and IDs to make IDs unique) and added an image ID for simplicity:

修复了 HTML(切换类和 ID 以使 ID 唯一)并为简单起见添加了图像 ID:

<div id="msgStyle1" class="message">Waiting for image</div>
<div id="imgStyle1" class="message">
    <img src="" id="image" />
</div>

JS:

JS:

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

See it work here: http://jsfiddle.net/N3rCm/

在这里看到它的工作:http: //jsfiddle.net/N3rCm/

回答by Brodie

First off, you shouldn't have multiple Id's on the page, it'll mess with your JS.

首先,您不应该在页面上有多个 Id,它会弄乱您的 JS。

Next I would give your image a class if you can

如果可以的话,接下来我会给你的形象上课

//jquery example of what you would do
var imgSrc = 'http://wherever/youre/getting/this/from';
$('.myimageclass').attr('src', imgSrc);

//non jquery
var myImg = document.getElementsByClassName('myimageclass')[0]; //assuming it's the first one
//or if you can uniquely identify it
var myImg = document.getElementById('imgId');

myImg.src = imgSrc;