【发布时间】:2013-02-14 20:46:51
【问题描述】:
当谈到 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()' ??
});
【问题讨论】:
-
请告诉我们你想用上面的代码实现什么。
-
我试图为任何不包含有效信息的输入字段模拟“临时突出显示”。 [对于表单验证脚本]。我注意到我认为我的确切代码有效,无论我传入的函数是否命名为“下一个”。有人可以解释这种行为吗?仅仅传入一个函数是不够的,你还必须在匿名函数内部调用它。我可以看到函数重载如何导致这种隐式的“dequeue()”行为,但触发器本身存在于匿名函数内部。
标签: javascript jquery anonymous-function