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

javascript - Assign img' src dynamically - Stack Overflow

programmeradmin3浏览0评论

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.

<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);
  };

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.

<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);
  };
Share Improve this question asked Mar 21, 2014 at 20:14 EmilyJEmilyJ 8922 gold badges8 silver badges20 bronze badges 1
  • Possible duplicate of stackoverflow.com/questions/20011721/… – Smeegs Commented Mar 21, 2014 at 20:22
Add a comment  | 

2 Answers 2

Reset to default 13

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

<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';

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

First off, you shouldn't have multiple Id's on the page, it'll mess with your 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;
发布评论

评论列表(0)

  1. 暂无评论