我试图创建两个计数器,当我按 downKey
时,我想 counter1 开始计数,当我按 keyLeft
时,我想停止第一个计数器并启动 counter2 ....我知道我需要使用 clearInterval()
函数,但我不知道在哪里需要使用它,这里是 JSFiddle
明白我的意思
html:
<div id="left"></div>
<div id="down"></div>
js:
$('body').keydown(function (e) {
switch (e.which) {
case 39:
clearInterval(down_move);
var i=0;
var right_move = setInterval(function(){
$('#left').html(i);
i++
}, 1000)
break;
case 40:
clearInterval(right_move);
var j = 0;
var down_move = setInterval(function(){
$('#down').html(j)
j++;
}, 1000);
break;
default:
}
e.preventDefault();
});
最佳答案
您需要在 keydown 之外声明 down_move 和 right_move:
var right_move, down_move;
$('body').keydown(function (e) {
switch (e.which) {
case 39:
clearInterval(down_move);
var i=0;
right_move = setInterval(function(){
$('#left').html(i);
i++
}, 1000)
break;
case 40:
clearInterval(right_move);
var j = 0;
down_move = setInterval(function(){
$('#down').html(j)
j++;
}, 1000);
break;
default:
}
e.preventDefault();
});
关于javascript - Jquery:使用 setInterval 进行计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34332329/