how to write a javascript variable as source for img tag in html
I have a variable that alternates from referencing different images. For example sometimes I have var imageName = "A.png"
. I want to set the innerHTML of a div tag to "src=" + imageName + ">"
but it doesn't work. When I used alert to get what the innerHTML actually was, I got this <img src="A" .png="">
. Why is this happening?
As per request here is my HTML code pertaining to this problem. It's part of a larger body of code which receives an xml file from a servlet. I find it weird that the for loop at the bottom works fine but the img src bit doesn't.
EDIT: I managed to get the innerHTML into the form <img src="/Users/adamsturge991/Desktop/webapp/Ass5/WEB-INF/classes/A.png">
by changing what the servlet wrote (I added the absolute path just to be sure that the file could be found.) However the picture still isn't loading. Odd
function displayResult(req)
{
var doc = req.responseText;
parser=new DOMParser();
xmlDoc=parser.parseFromString(doc,"text/xml");
var imageName = xmlDoc.getElementsByTagName('ImageName').item(0).textContent + ".png";
var comments = xmlDoc.getElementsByTagName('Comment');
var imgDisplay = document.getElementById('ImageDisplay');
var str = "<img src=" + imageName + ">";
alert(str);
imgDisplay.innerHTML = str;
alert(imgDisplay.innerHTML);
str = '';
for (var j = 0; j < comments.length; j++)
{
str = str + "<p>"+ comments.item(j).textContent + "</p>";
}
var commentDisplay = document.getElementById('CommentDisplay');
commentDisplay.innerHTML = str;
}
I found this example useful:
var url = "www.example.com/image.jpg";
var img = new Image();
img.src = url;
document.body.appendChild(img);
You just need to make some tweaks to adjust to your needs
I think this line is wrong:
var str = "<img src=" + imageName + ">";
This will render as:
<img src=A.png>
But this could confuse the browset It probably should be:
var str = "<img src="" + imageName + "" />";
(that is, quote the attribute value, and for good measure, close the tag.)
This renders as:
<img src="A.png" />
链接地址: http://www.djcxy.com/p/47932.html
上一篇: 将数组数据作为对象附加到json文件