jQuery setInterval / hovering:它工作一次,但随后停止setInterval

时间:2011-04-11 13:31:57

标签: jquery hover setinterval


我的'setInterval'函数有问题,我想在我徘徊我的div时启动该函数,但是setInterval只是在我第一次使用div =>时工作如果我留在div上,它不会继续改变图片,而是停止'setinterval'。

这是mouseenter的问题吗?我试过'悬停'等等,但似乎没有什么可以成功的。

有没有人有解决方案?

非常感谢您的帮助,这是我的代码:

img.bind('mouseenter', function(){
    setInterval(next($(this)),1000);
});

function next(elem){  
    var img_li = elem.find('li');  
    count++;  
    if (count>2) count=0;  

    img_li.eq(count).fadeIn('fast', function(){  
        img_li.eq(current).css({'display':'none'});

        current = count;  
    });  
}

2 个答案:

答案 0 :(得分:2)

这是因为你将next($(this))的返回值赋给setInterval而不是函数本身。

试试这个:

img.bind('mouseenter', function(){     
    var that = $(this); //Use that-this model to avoid any scope issues with this reference
    setInterval(function(){
        next(that);
    },1000); 
}); 

答案 1 :(得分:2)

您可以考虑使用jQuery Timers插件,这样可以更轻松地使用此类功能。特别是,请看以下内容:

  

everyTime(interval:Integer | String,[label = interval:String],fn:Function,[times = 0:Integer])

     

everyTime将定义的函数(fn)添加为定时事件,以给定的时间间隔(间隔)运行给定的次数(次数)。如果times设置为0,则调用方法的次数是无限的。还为给定的定时事件设置标签,提供给提供的字符串(标签)或提供的间隔的字符串表示。此外,可以使用诸如“3s”之类的字符串定义间隔3秒钟。

相关问题