以下代码中的全局变量的替代

时间:2015-10-14 16:17:15

标签: javascript global-variables

我的任务是创建一个HTML按钮,根据按下按钮的次数在页面上显示不同的消息。我下面的代码包含一个全局变量(计数器)来计算按下按钮的次数。代码有效,但我读过你应该避免使用全局变量。

var counter = 0; // global variable

window.onload = function() {
  document.getElementById("button").onclick = go;
}

function go() {
  counter++
  switch(counter) {
    case 1:
      document.getElementById("output").textContent = "You pushed the button.";
      break;
    case 2:
      document.getElementById("output").textContent = "You pushed the button (again).";
      break;
    case 3:
    case 4:
    case 5:
      document.getElementById("output").textContent = "You pushed the button "
  + counter.toString() + " times.";
      break;
    default:
      document.getElementById("output").textContent = "Stop pushing the button."
  }
}

我读了Define global variable in a JavaScript function,它表示将函数(我的情况下为go)包含在一个“范围函数”中,全局变量直接位于其中,如下所示:

window.onload = function() {
  document.getElementById("button").onclick = go;
}
(function() {
  var counter = 0; // Global now inside the scoping function
  function go() {
    counter++
    switch(counter) {
      case 1:
        document.getElementById("output").textContent = "You pushed the button.";
        break;
      case 2:
        document.getElementById("output").textContent = "You pushed the button (again).";
        break;
      case 3:
      case 4:
      case 5:
        document.getElementById("output").textContent = "You pushed the button "
    + counter.toString() + " times.";
        break;
      default:
        document.getElementById("output").textContent = "Stop pushing the button."
    }
  }
})();

但是当我尝试我的代码根本不起作用时。有什么建议吗?

1 个答案:

答案 0 :(得分:2)

你的window.onload应该在包装器的范围内。

(function() {
  window.onload = function() {
  document.getElementById("button").onclick = go;
  }

  var counter = 0; // Global now inside the scoping function
  function go() {
    counter++
    switch(counter) {
      case 1:
        document.getElementById("output").textContent = "You pushed the button.";
        break;
      case 2:
        document.getElementById("output").textContent = "You pushed the button (again).";
        break;
      case 3:
      case 4:
      case 5:
        document.getElementById("output").textContent = "You pushed the button "
    + counter.toString() + " times.";
        break;
      default:
        document.getElementById("output").textContent = "Stop pushing the button."
    }
  }
})();