"document.getElementById”;不起作用

"document.getElementById" is not working

本文关键字:不起作用 getElementById document quot      更新时间:2023-09-26

我正在使用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>

四个问题:

  1. 您需要在处理程序中调用count

    <button type="button" onclick="count()">Test_Function</button>
    
  2. counter =! 3应该是counter != 3,否则您将其设置为false

  3. counter + 1什么都不做。使用counter += 1counter++
  4. 不要将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>