html 图像 src 调用 javaScript 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35149719/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:19:25  来源:igfitidea点击:

html image src call javaScript variable

javascripthtml

提问by Neo

this is my code: I want to ask

这是我的代码:我想问

<script type="text/javascript">

var total = 4;

</script>

How can I do this?

我怎样才能做到这一点?

<img src="img/apple_" + total + ".png" id="imageBox"/>

I've been try to use call function and document.onload but it's not work at all, can somebody save me?

我一直在尝试使用 call 函数和 document.onload 但它根本不起作用,有人可以救我吗?

回答by kp singh

I am supposing you just want to update the image src with javascript.

我假设您只想用 javascript 更新图像 src。

document.getElementById('imageBox').src = "img/apple_" + total + ".png";

回答by jcubic

You need to add html in JavaScript like this:

您需要像这样在 JavaScript 中添加 html:

<div id="foo"></div>
<script type="text/javascript">

var total = 4;
document.getElementById('foo').innerHTML = '<img src="img/apple_' + total + '.png" id="imageBox"/>';
</script>

回答by Sunil Kumar

window.onload = function() {
  var total = 4;
  document.getElementById('imageBox').src = 'img/apple_' + total + '.png"';

};
<img src="" id="imageBox"/>

回答by kemicofa ghost

Here is a clean way to do this.

这是一个干净的方法来做到这一点。

Demo

演示

var create_img_element = function(total, targetId){
    //create the img element
    var img = document.createElement('img');
    //set the source of the image
    img.src = 'img/apple_' + total + '.png';
    //add the image to a specific element
    document.getElementById(targetId).appendChild(img);
}

create_img_element(5, 'foo');