带有延迟的 jQuery 切换类只工作一次 [英] jQuery toggle class with delay works only once

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

问题描述

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

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

var jElement = $(currElem);jElement.addClass("突出显示").延迟(1000).队列(功能(){$(this).removeClass("highlight");});

然而,

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

var jElement = $(currElem);jElement.addClass("突出显示").延迟(1000).queue(函数(随机函数){$(this).removeClass("highlight");随机函数();//这让它看起来奇迹般地"起作用了??});

旁注:

var jElement = $(currElem);jElement.addClass("突出显示").延迟(1000).queue(函数(随机函数){$(this).removeClass("highlight");//这不起作用;如果我实际上不调用randomFunction"//所以这个函数,即使它什么都不做;必须以某种方式导致//'dequeue()' 的隐式调用 ??});

解决方案

没有奇迹.这种行为写在 .queue() 的文档中.><块引用>

注意添加带有.queue()的函数时,要保证.dequeue()> 最终被调用,以便执行下一个函数.

$('#foo').slideUp().queue(function() {alert('动画完成.');$(this).dequeue();});

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

$("#test").queue(function(next) {//做一些事情...下一个();});

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

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,

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

Side Note:

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

解决方案

There is no miracle there. This behavior it's written in the documentation of .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();
});

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

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