在jQuery的live事件mouseOver / mouseOut中使用setInterval

时间:2010-12-06 17:03:45

标签: javascript jquery

嘿伙计们!
我试图在用户mouseOver元素时启动一个计时器并在mouseOut上停止它。这些元素是动态创建的,这就是使用live方法的原因。

所以我的计时器正确启动,但我无法阻止它!怎么了?

$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);
        }
    });

1 个答案:

答案 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'));
});