jQuery 切换类名带有延迟只能工作一次

3

在涉及到jQuery、匿名函数和延迟时,我显然缺少一些基础知识。下面的代码每次页面加载只能工作一次(它将添加类,然后在1秒后将其移除,如果我再次点击,它将添加类,但在页面持续期间将永远不会删除该类,除非重新加载页面):

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

然而,如果我将(不存在的)函数调用作为参数添加,并在匿名函数中调用它,则添加/删除类组合将无限期地工作。

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

请告诉我们,您想通过以上代码实现什么目标。 - Venemo
我试图模仿一个“临时高亮”来标识任何不包含有效信息的输入字段。[用于表单验证脚本]。我注意到,我的确切代码可以工作,无论我传递的函数是否命名为“next”。有人能解释一下这种行为吗?仅传递函数是不够的,您还必须在匿名函数内部调用它。我可以看出函数重载可能会导致这种隐式的“dequeue()”行为,但触发器本身存在于匿名函数内部。 - Stevers
2个回答

5

这并没有什么神奇的地方。这种行为在.queue()文档中有所说明。

Note that when adding a function with .queue(), we should ensure that .dequeue() is eventually called so that the next function in line executes.

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

As of jQuery 1.4, the function that's called is passed another function as the first argument. When called, this automatically dequeues the next item and keeps the queue moving. We use it as follows:

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

谢谢大家的快速回复。我确实查看了queue()的API,但在接近dequeue()和next()解释时,我感到非常不知所措。我很少寻求帮助,通常通过像这样的网站自己找到答案,但这个问题已经困扰我一段时间了,所以我注册并提问了。我真的很喜欢这个社区,并且一旦我感到已经掌握了jQuery(和其他语言)的基础知识,肯定会贡献我的力量。 - Stevers

2

randomFunction实际上被称为next,它引用了.dequeue方法。调用它会导致队列继续执行下一个项目。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接