根据变量内容替换图片的跨度值

时间:2017-02-17 08:04:04

标签: javascript html loops

在我的网页中,我有几个跨度,需要根据相关的变量值将它们替换为图片:

for(i = 1; i <= 5 ; i++)		
document.getElementById('state_'+i).innerHTML = '<img src="picture_' + "~varstate("+i+")~" + '.png"></img>';
<span id ="state_1">?</span>
<span id ="state_2">?</span>
<span id ="state_3">?</span>
<span id ="state_4">?</span>
<span id ="state_5">?</span>

varstate(1); varstate(2); varastate(3); varastate(4); varastate(5) 是变量,它们只能获得0或1个值。

然后,我需要将每个跨度内容替换为:picture_0.png或picture_1.png,具体取决于varstate值。

循环不起作用,请你告诉我为什么?

1 个答案:

答案 0 :(得分:0)

也许这个?

<span id="state_1">?</span>
<span id="state_2">?</span>
<span id="state_3">?</span>
<span id="state_4">?</span>
<span id="state_5">?</span>

<script>
    for (let i = 1; i <= 5 ; i++)
        document.getElementById('state_' + i).innerHTML = '<img src="picture_' + varstate(i) + '.png" />';
</script>