我正在使用HTML和JavaScript编写一组交通灯,我遇到了一个问题。我创建了一个按钮,它应该将网站上的一行文本更改为一个数字,但无论何时单击它都不会执行任何操作。我认为这是document.getElementById
脚本的一个问题,因为我不认为它可能是其他任何东西。这是我的代码:
<p id="dummy">PLACEHOLDER</p>
<script>
var imgArray = ["img0", "img1", "img2", "img3"];
imgArray[0] = new Image(300, 150);
imgArray[0].src = "Assets/TrafficLightRedLight.jpg";
imgArray[1] = new Image(300, 150);
imgArray[1].src = "Assets/TrafficLightRedAmberLight.jpg";
imgArray[2] = new Image(300, 150);
imgArray[2].src = "Assets/TrafficLightAmberLight.jpg";
imgArray[3] = new Image(300, 150);
imgArray[3].src = "Assets/TrafficLightGreenLight.jpg";
var counter = 0;
function count(counter){
if (counter =! 3){
counter + 1;
}
else{
counter = 0;
}
document.getElementById("dummy").innerHTML = counter;
}
</script>
<button type="button"
onclick="count">Test_Function</button>
答案 0 :(得分:3)
四个问题:
您需要在处理程序中调用 count
:
<button type="button" onclick="count()">Test_Function</button>
counter =! 3
应为counter != 3
,否则您将其设置为false
counter + 1
没有做任何事情。使用counter += 1
或counter++
counter
作为参数 - 您只需修改本地副本。以上所有修正:
<p id="dummy">PLACEHOLDER</p>
<script>
var imgArray = ["img0", "img1", "img2", "img3"];
var counter = 0;
imgArray[0] = new Image(300, 150);
imgArray[0].src = "Assets/TrafficLightRedLight.jpg";
imgArray[1] = new Image(300, 150);
imgArray[1].src = "Assets/TrafficLightRedAmberLight.jpg";
imgArray[2] = new Image(300, 150);
imgArray[2].src = "Assets/TrafficLightAmberLight.jpg";
imgArray[3] = new Image(300, 150);
imgArray[3].src = "Assets/TrafficLightGreenLight.jpg";
function count() {
if (counter != 3) {
counter++;
} else {
counter = 0;
}
document.getElementById("dummy").innerHTML = counter;
}
</script>
<button type="button" onclick="count()">Test_Function</button>
&#13;