我已经设置了一个setInterval来使用不同的css类来改变div的颜色。我通过按下按钮开始改变颜色,但我也想停止使用相同的按钮改变颜色。我无法让它发挥作用。这是我的js:
var bsstyles = ["alert alert-success","alert alert-info","alert alert-warning","alert alert-danger"];
var i = 0;
var buttonstate = false;
var runner;
var mainfun = function () {
if (buttonstate == 0) {
buttonstate = true;
document.getElementById("changebutton").className = "btn btn-primary btn-lg active";
var runner = setInterval(function() {
document.getElementById("alertw").className = bsstyles[i];
i++;
if (i==bsstyles.length) {
i=0;
}
},1000);
} else {
clearInterval(runner);
document.getElementById("changebutton").className = "btn btn-primary btn-lg";
buttonstate = false;
}
}
var changeButton = document.getElementById("changebutton");
changeButton.addEventListener('click',mainfun,false);
以下是JSFiddle
答案 0 :(得分:4)
定义mainfun
时,需要在'runner'
通过使用var关键字,您将定义一个不再引用全局变量runner的新局部变量
所以代码看起来像
var bsstyles = ["alert alert-success","alert alert-info","alert alert-warning","alert alert-danger"];
var i = 0;
var buttonstate = false;
var runner;
var mainfun = function () {
if (buttonstate == 0) {
buttonstate = true;
document.getElementById("changebutton").className = "btn btn-primary btn-lg active";
runner = setInterval(function() {
document.getElementById("alertw").className = bsstyles[i];
i++;
if (i==bsstyles.length) {
i=0;
}
},1000);
} else {
clearInterval(runner);
document.getElementById("changebutton").className = "btn btn-primary btn-lg";
buttonstate = false;
}
}
var changeButton = document.getElementById("changebutton");
changeButton.addEventListener('click',mainfun,false);
答案 1 :(得分:2)
我经常在函数本身上存储Interval句柄(假设我知道只有一个实例):
mainfun.runner = setInterval(function () {
//Content
}, 1000);
clearInterval( mainfun.runner );
这可以防止有一个全球性的跑步者' var可能会被意外覆盖。 (当然,mainfun.runner也是全球可访问的,但不太可能被意外写入。)
答案 2 :(得分:1)
所有其他答案都指出了实际问题,用本地变量覆盖了一个全局变量,但我想我会简化你的代码:
var runner = null, i = 0;
var changeClassById = function(id, className) {
document.getElementById(id).className = className;
};
var mainfun = function () {
if (runner) {
clearInterval(runner);
changeClassById("changebutton", "btn btn-primary btn-lg");
runner = null;
} else {
changeClassById("changebutton", "btn btn-primary btn-lg active");
runner = setInterval(function() {
changeClassById("alertw", bsstyles[++i % bsstyles.length]);
}, 1000);
}
}
更少的代码行意味着搞砸的可能性更小。
答案 3 :(得分:0)
您正在if语句中重新定义runner
。移除var
:http://jsfiddle.net/g6to2gqn/2/
答案 4 :(得分:0)
您正在声明间隔跑步者的变量;
只需删除第var runner = setInterval(function() {
行