带延迟的jQuery toggle类只能运行一次

在jQuery,匿名函数和延迟方面,我显然缺少一些基本的东西。

以下代码仅适用于每页加载ONCE(它将添加该类,然后在1秒后删除它,如果我再次单击,它将添加该类,但绝不会在页面持续时间内删除该类,除非我重新加载页面):

var jElement = $(currElem); jElement.addClass("highlight") .delay(1000) .queue(function(){ $(this).removeClass("highlight"); }); 

然而,

如果我将(非existant)函数调用作为参数添加,并且我在我的匿名函数中调用它,那么add / remove类组合将无限期地工作。

 var jElement = $(currElem); jElement.addClass("highlight") .delay(1000) .queue(function(randomFunction){ $(this).removeClass("highlight"); randomFunction(); //this makes it seemingly 'miraculously' work?? }); 

边注:

 var jElement = $(currElem); jElement.addClass("highlight") .delay(1000) .queue(function(randomFunction){ $(this).removeClass("highlight"); // this does NOT work; if I dont actually call the 'randomFunction' // so that function, even though it does nothing; must somehow cause // the implicit call of 'dequeue()' ?? }); 

那里没有奇迹。 这种行为是在.queue()的文档中.queue()

注意,当使用.queue()添加函数时,我们应该确保最终调用.dequeue()以便行中的下一个函数执行。

 $('#foo').slideUp().queue(function() { alert('Animation complete.'); $(this).dequeue(); }); 

从jQuery 1.4开始 ,被调用的函数将另一个函数作为第一个参数传递。 调用时,会自动将下一个项目出列并使队列保持移动状态。 我们用它如下:

 $("#test").queue(function(next) { // Do some stuff... next(); }); 

randomFunction实际上称为next并引用.dequeue方法。 调用它会使队列继续到队列中的下一个项目。

http://api.jquery.com/queue/