动态分配img的src

时间:2014-03-21 20:14:47

标签: javascript html

该页面将正确显示图片的网址文字。但我不知道如何将消息分配给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);
  };

2 个答案:

答案 0 :(得分:3)

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

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

JS:

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

在此处查看:http://jsfiddle.net/N3rCm/

答案 1 :(得分:1)

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

接下来,如果你能

,我会给你的形象上课
//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;