我正在尝试使计数器在10秒内达到100,然后循环。我的代码出了什么问题?
window.onload = function () {
var showPercent = window.setInterval(function () {
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
document.getElementById('result').innerHTML = currentPercent;
}, 100);
};
答案 0 :(得分:4)
答案 1 :(得分:0)
var currentPercent = 0;
setInterval(function() {
if (currentPercent < 100) {
currentPercent += 1;
} else {
currentPercent = 0;
}
document.getElementById('result').innerHTML = currentPercent;
}, 100);
答案 2 :(得分:0)
在你的小提琴中你已经让它运行onload。您的代码段的问题是currentPercent
需要存在于setInterval回调范围之外:
var currentPercent = 0;
var showPercent = window.setInterval(function() {
if (currentPercent < 100) {
++currentPercent;
} else {
currentPercent = 0;
}
document.getElementById('result').innerHTML = currentPercent;
}, 100);
答案 3 :(得分:0)
在启用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);
};