“document.getElementById”无效

时间:2015-12-05 20:46:27

标签: javascript html

我正在使用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 个答案:

答案 0 :(得分:3)

四个问题:

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

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

  3. counter + 1没有做任何事情。使用counter += 1counter++
  4. 请勿使用counter作为参数 - 您只需修改本地副本。
  5. 以上所有修正:

    &#13;
    &#13;
    <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;
    &#13;
    &#13;