Javascript 以 HTML 格式返回图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26912829/
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
return image as HTML
提问by John
trying to add an image to my innerHTML.
试图将图像添加到我的innerHTML。
Looked at a few prvious Q's Why does my image not show up when I use Javascript innerHTML to call it?
看了几个之前的Q's 为什么我的图片在使用Javascript innerHTML 调用时不显示?
Javascripts innerHTML not working for images, but works with text?
JavascriptsinnerHTML 不适用于图像,但适用于文本?
I cant get it working, in google dev tools throws the error:
我无法让它工作,在谷歌开发工具中抛出错误:
Uncaught TypeError: Cannot set property 'innerHTML' of null
with this line:
用这一行:
var newImage = document.getElementById('img').innerHTML = "<img src='images/bg-main.png></img>";
my code looks like:
我的代码看起来像:
function showImage() {
var img = document.createElement('image');
//var newImage = document.getElementById('img').innerHTML = "<a href='#'><img src='http://mintywhite.com/wp-content/uploads/2012/10/fond-ecran-wallpaper-image-arriere-plan-hd-29-HD.jpg' border=0/></a>";
var newImage = document.getElementById('img').innerHTML = "<img src='images/bg-main.png></img>";
var div5 = document.createElement('div');
div5.appendChild(newImage);
return div5.innerHTML;
}
I know there are many other methods to display an image, but for the purpose of this exercise I want to return the image as an innerHTML
我知道还有许多其他方法可以显示图像,但是为了本练习的目的,我想将图像作为 innerHTML 返回
采纳答案by BastienSander
Try this :
尝试这个 :
var img = document.createElement("img");
img.setAttribute('src', 'http://www.domain.com/imgSrc');
var div5 = document.createElement('div');
div5.appendChild(newImage);
回答by Kevin Kuyl
document.createElement('image')creates a new html tag: <image>i suspect you're trying to add a div and apply the image as inner html. you can fix this code like the following:
document.createElement('image')创建一个新的 html 标签:<image>我怀疑您正在尝试添加一个 div 并将图像应用为内部 html。您可以像下面这样修复此代码:
function showImage() {
var img = document.createElement('div');
document.body.appendChild(img)
img.innerHTML = "<img src='images/bg-main.png></img>";
}

