所以我的计时器正确启动,但我无法阻止它!怎么了?
$elems.live('mouseover mouseout', function(event) {
var self = $(this), i = 0;
if (event.type == 'mouseover') {
var timer = setInterval(function() {
// change the src of the current element for an element of an array of src, much like in a slideshow
self.attr('src', tabSrc[i]);
i === 2 ? i = 0 : i++;
}, 1000);
}
// Handle the mouseOut
else {
// stop the timer <------ when I mouseOut the element, this doesn't seems to work...
clearInterval(timer);
}
});
答案 0 :(得分:5)
您的timer
变量的范围不正确,它必须位于处理程序之外,如下所示:
var timer;
$elems.live('mouseover mouseout', function(event) {
var self = $(this), i = 0;
if (event.type == 'mouseover') {
timer = setInterval(function() {
self.attr('src', tabSrc[i]);
i === 2 ? i = 0 : i++;
}, 1000);
}
else {
clearInterval(timer);
}
});
或者,或者使用$.data()
来存储每个元素的间隔,如下所示:
$elems.live('mouseover', function() {
var self = $(this), i = 0;
$.data(this, 'timer', setInterval(function() {
self.attr('src', tabSrc[i]);
i === 2 ? i = 0 : i++;
}, 1000));
}).live('mouseout', function() {
clearInterval($.data(this, 'timer'));
});