问题描述
我正在尝试通过其自身更改div的left属性-当您将鼠标悬停在div上时,每秒更改一次,所以我这样做了:
I'm trying to have a div's left property change by its self - one every second when your hovering over so I made this:
$("div.scroll_left").hover(function(){
var left_num = $('div.license_video').css("left")
var left_num1 = parseInt(left_num, 10) - 1;
var timerID = setInterval(alert(left_num1), 1000);
//var timerID = setInterval(slideleft(left_num1), 1000);
},function(){
clearInterval(timerID);
});
//function slideleft(left_num){
//$('.license_video').css('left', left_num + "%");
//}
理论上,您会认为它会重复执行,直到您将光标移开以清除间隔为止.当我将鼠标悬停在它上面时,它一次不会重复(没有错误).然后,当我将鼠标悬停时,会出现错误未捕获的ReferenceError:未定义timerID"
In theory you would think it repeat till you move your cursor off which clears the interval. When I hover over it does it one time and never repeats (there are no errors). Then when I hover off it gives a error "Uncaught ReferenceError: timerID is not defined"
推荐答案
因此,您在这里遇到了两个不同的问题:
So you've got two different problems here:
// (1) timerID needs to be defined in a scope accessible to both hover callbacks
var timerID = null;
$("div.scroll_left").hover(function(){
var left_num = $('div.license_video').css("left")
var left_num1 = parseInt(left_num, 10) - 1;
// (2) Pass a *function* to setInterval
timerID = setInterval(function () {
alert(left_num1)
}, 1000);
}, function(){
clearInterval(timerID);
timerID = null;
});
写作时
setInterval(alert(left_num1), 1000);
// or
setInterval(slideleft(left_num1), 1000);
您正在将分别调用alert()
或slideleft()
的返回值传递给setInterval
.您不传递函数本身.
you are passing the value returned by calling alert()
or slideleft()
(respectively) to setInterval
. You are not passing the function itself.
这篇关于setInterval()不重复.只工作1次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!