Javascript 如何通过innerHTML设置图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36859062/
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
How to set image via innerHTML
提问by WhoIsDT
Confusing question...
困惑的问题...
In echo i have blank page.. if i set innerHTML="some text"; - it works. Why it's not working with image? If i directly goes to https://domain.com/adv/banner.jpgit will open image...
在 echo 我有空白页.. 如果我设置了 innerHTML="some text"; - 有用。为什么它不适用于图像?如果我直接访问https://domain.com/adv/banner.jpg它将打开图像...
echo'
<div id="yabanner"></div>
<script>
yaGetBanner();
function yaGetBanner()
{
var el = document.getElementById("yabanner");
el.innerHTML="<img src=\'https://domain.com/adv/banner.jpg\' width=\'400px\' height=\'150px\'>";
}
</script>
';
回答by Variable
You need double quotes
for the img
attribute too, and then you need the backslashes
. So your code would look like:
您也需要double quotes
该img
属性,然后您需要backslashes
. 所以你的代码看起来像:
echo '
<div id="yabanner"></div>
<script>
yaGetBanner();
function yaGetBanner()
{
var el = document.getElementById("yabanner");
el.innerHTML="<img src=\"http://placehold.it/350x350\" width=\"400px\" height=\"150px\">";
}
</script>';
Also note that you have
banner
andadv
in the name of your image URL. Adblockers will block these images or addinline
styling to yourimg
attributes containing that image.
另请注意,您在图像 URL 的名称中有
banner
和adv
。Adblockers 将阻止这些图像或inline
为img
包含该图像的属性添加样式。
I hope this help!
我希望这有帮助!