繁体   English   中英

为什么这个JavaScript计数器无法运作?

[英]Why isn't this javascript counter working?

我正在尝试制作一个计数器,该计数器在10秒内上升到100,然后循环。 我的代码有什么问题?

window.onload = function () {
    var showPercent = window.setInterval(function () {
        if (currentPercent < 100) {
            currentPercent += 1;
        } else {
            currentPercent = 0;
        }

        document.getElementById('result').innerHTML = currentPercent;
    }, 100);
};

http://jsfiddle.net/JBVA2/

您无需在代码的任何位置声明currentPercent ,而应添加如下内容: var currentPercent = 0; showPercent之前

JSBin演示

var currentPercent = 0;  

setInterval(function() {
    if (currentPercent < 100) {
       currentPercent += 1;
    } else {
       currentPercent = 0;
    }

    document.getElementById('result').innerHTML = currentPercent;
}, 100);

在您的小提琴中,您已经可以让它在加载时运行。 您的代码段存在的问题是currentPercent需要在setInterval回调范围之外存在:

var currentPercent = 0;
var showPercent = window.setInterval(function() {
  if (currentPercent < 100) {
    ++currentPercent;
  } else {
    currentPercent = 0;
  }

 document.getElementById('result').innerHTML = currentPercent;
}, 100);

http://jsfiddle.net/JBVA2/4/

在启用了Firebug的Firefox中加载页面时出现以下错误:

ReferenceError:未定义currentPercent

您正在将变量currentPercent中存储的值与“ 100”进行比较,但尚未定义该变量。 对代码进行一些小的改动就可以使其正常工作:

  var currentPercent = 0;
  window.onload = function() {
    var showPercent = window.setInterval(function() {
      if (currentPercent < 100) {
        currentPercent += 1;
      }

      document.getElementById('result').innerHTML = currentPercent;
    }, 100);
  };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM