在jQuery的实时事件中使用setInterval mouseOver/mouseOut [英] Using setInterval in jQuery's live events mouseOver/mouseOut

查看:104
本文介绍了在jQuery的实时事件中使用setInterval mouseOver/mouseOut的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!
我正在尝试在用户mouseOver元素上启动计时器并将其停在mouseOut上.这些元素是动态创建的,这就是使用live方法的原因.

Hey guys!
I'm trying to start a timer when a user mouseOver an element and stop it on the mouseOut. The elements are created dynamically, which is the reason the use of the live method.

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

So my timer starts correctly, but I can't stop it! What's wrong?

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

推荐答案

您的timer变量的作用域不正确,它必须位于处理程序之外,如下所示:

Your timer variable isn't scope correctly, it needs to be outside the handler, like this:

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() 来存储每个元素的间隔,如下所示:

Or, alternatively use $.data() to store an interval per element, like this:

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

这篇关于在jQuery的实时事件中使用setInterval mouseOver/mouseOut的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆