带延迟的jQuery toggle类只能运行一次 [英] jQuery toggle class with delay works only once

查看:65
本文介绍了带延迟的jQuery toggle类只能运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当涉及到jQuery,匿名函数和延迟时,我显然缺少一些基本的东西。

I am clearly missing something fundamental when it comes to jQuery, anonymous functions, and delays.

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

The following code works only ONCE per page load (it will add the class, then remove it after 1 second, and if i click again, it will add the class, but will NEVER remove the class for the duration of the page, unless I reload the page):

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

HOWEVER,

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

if I add the (non-existant) function call as a parameter, AND I call it in my anonymous function, then the add/remove class combination will work indefinitely.

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() <的文档中/ a>。

There is no miracle there. This behavior it's written in the documentation of .queue().


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

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

从jQuery 1.4 开始,被调用的函数被传递给另一个函数as第一个论点。调用时,会自动使下一个项目出列并使队列保持移动状态。我们按如下方式使用它:

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


这篇关于带延迟的jQuery toggle类只能运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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