这是我的代码:我想问一下
<script type="text/javascript">
var total = 4;
</script>
我该怎么做?
<img src="img/apple_" + total + ".png" id="imageBox"/>
我一直尝试使用call function和document.onload,但它根本不起作用,有人可以救我吗?
答案 0 :(得分:5)
我想你只想用javascript更新图像src。
document.getElementById('imageBox').src = "img/apple_" + total + ".png";
答案 1 :(得分:2)
您需要在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>
答案 2 :(得分:0)
这是一种干净的方法。
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');
答案 3 :(得分:0)
window.onload = function() {
var total = 4;
document.getElementById('imageBox').src = 'img/apple_' + total + '.png"';
};
<img src="" id="imageBox"/>