为什么我的图片在使用 Javascript innerHTML 调用时不显示?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9524458/
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
Why does my image not show up when I use Javascript innerHTML to call it?
提问by biobio
I am pretty new to Javascript, and I was trying somethings out. I am using a function to load an image inside a table using innerHTML. But the image does not show up, unless I call alert("whatever") at the bottom of the function, then it shows up while the alert is visible. The code I am using is something like (the function is called from an external js file)
我对 Javascript 很陌生,我正在尝试一些东西。我正在使用一个函数来使用innerHTML 在表格中加载图像。但是图像不显示,除非我在函数底部调用 alert("whatever"),然后它会在警报可见时显示。我使用的代码类似于(该函数是从外部 js 文件调用的)
<script>
function show(){
document.getElementById('imageHolder1').innerHTML="<a href="#"><img='photos/picture.jpg' border=0/></a>";
}
</script>
<body> <input name="b1" type="button" value="pics" onclick="show()"/>
<table><td id='imageHolder1'>picture</td></table>
</body> ``
I don't understand why it doesn't work, all the examples i have looked at are similar, I see no big differences.Even if I try with out the tag it doesn't work. Well any help welcome! Thanks in advance, and if you have any suggestions on how to do this (no jquery since I am still learning javascript) I would also appreciate it. Thanks again!
我不明白为什么它不起作用,我看过的所有例子都是相似的,我看不出有什么大的不同。即使我尝试不使用标签它也不起作用。好吧,欢迎任何帮助!提前致谢,如果您对如何执行此操作有任何建议(没有 jquery,因为我仍在学习 javascript),我也将不胜感激。再次感谢!
回答by St.Woland
You have an error in your string:
您的字符串中有错误:
document.getElementById('imageHolder1').innerHTML="<a href="#"><img='photos/picture.jpg' border=0/></a>";
Should read
应该读
document.getElementById('imageHolder1').innerHTML="<a href='#'><img src='photos/picture.jpg' border=0/></a>";
(notice " to ' replacement)
(注意“到 ' 替换)
回答by mindandmedia
there are LOTS of errors and lazy shortcuts in your code. i made a fiddle and had to correct quite a few places that looks like very hasty work... here is your fiddle, but play it with some devotion: http://jsfiddle.net/uXpeK/
您的代码中有很多错误和懒惰的快捷方式。我做了一个小提琴,不得不纠正很多看起来非常仓促的地方......这是你的小提琴,但要投入一些精力:http: //jsfiddle.net/uXpeK/
回答by clem
you aren't adding the image src. and it should be href='#'
it should be like this
您没有添加图像 src。它应该是href='#'
它应该是这样的
function show(){
document.getElementById('imageHolder1').innerHTML="<a href='#'><img src='photos/picture.jpg' border='0'/></a>";
}
回答by Hyman
Try giving the image an id of 'image' then using the following:
尝试给图像一个 'image' id,然后使用以下命令:
function show(){
document.getElementById('image').src = 'photos/picture.jpg'
}