[英]html image src call javaScript variable
這是我的代碼:我想問一下
<script type="text/javascript">
var total = 4;
</script>
我怎樣才能做到這一點?
<img src="img/apple_" + total + ".png" id="imageBox"/>
我一直在嘗試使用call函數和document.onload,但它根本不起作用,有人可以救我嗎?
我想你只是想用javascript更新圖像src。
document.getElementById('imageBox').src = "img/apple_" + total + ".png";
您需要在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>
window.onload = function() { var total = 4; document.getElementById('imageBox').src = 'img/apple_' + total + '.png"'; };
<img src="" id="imageBox"/>
這是一個干凈的方法來做到這一點。
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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.