【问题标题】:Queue jQuery events/actions across multiple elements跨多个元素排队 jQuery 事件/动作
【发布时间】:2012-12-11 20:28:24
【问题描述】:

我有一个带有以下标记的 HTML 文档:

<div id="outside">
<div id="warning">Some warning here</div>
<div id="inside"></div>
</div>

我想做的是这个列表,按照列出的顺序,在前一个完成之前不继续下一个:

  1. 隐藏#outside 元素。
  2. 将#inside 的内容设置为“foo”。
  3. 显示#outside 元素。

这样的事情可以用 jQuery 来完成:

$('#outside').hide(function(){
    $('#inside').html('bar');
    $('#outside').show();
});

随着更多事件包含回调,这段代码变得更加混乱,并且变得不容易维护。

相反,我想做这样的事情:

$.sequence(
    function(){ $('#outside').hide(); },
    function(){ $('#inside').html('foo'); },
    function(){ $('#outside').show(); }
);

此代码清楚地显示了流程的每个步骤,并且允许轻松插入/删除任何步骤,因为它不需要嵌套函数回调。

请注意,此处显示的 HTML 与我实际使用的内容相比已大大简化,并且我希望对这些元素应用更长的操作链。

通常,这仅通过对同一 jQuery 元素的顺序方法调用是可能的,但是使用的不同元素不允许队列按顺序执行。我正在寻找一种对调用进行排序的方法,这种调用在读取时看起来很干净并且可以与任何元素一起使用。

【问题讨论】:

  • .hide().show() 是即时的,不需要回调。但可能你正在寻找.queue

标签: javascript jquery queue


【解决方案1】:

在这个特定的例子中,它相对容易。您可以通过以下方式获得所需的结果:

$('#outside').hide();
$('#inside').html('foo');
$('#outside').show();

但是,如果你抛出异步事件,这显然是行不通的。假设您想使用 ajax 获取“foo”。这将是一种相对常见的方式。

// request for content immediately
var req = $.get("myfile.php");
// fade out container
$("#outside").fadeOut(function(){

    // now that the container is faded out, we
    // bind to the done callback of the request
    // so that we can use the response and fadeIn the container
    // as soon as possible without causing an abrupt stop of the animation
    // if the request finishes early (it most likely will).
    req.done(function(response){
        $("#inside").html(response);
        $("#outside").fadeIn();
    });
});

除非您不习惯使用延迟对象,否则没有什么是难以阅读的。它会产生少量代码,以尽可能快的速度检索和显示内容,并带有微妙的动画。

如果你真的想让它“看起来更好”,你当然可以在函数后面抽象出这个方法,但它可能最终变得更难维护(我在哪里定义了那个函数?

【讨论】:

  • 确实如此。中间位用于模拟异步事件。我喜欢使用延迟对象的方式,但是如果要发出多个请求,它仍然会导致嵌套函数混乱,不是吗?
  • 不,您只需使用 $.when 将两者组合成一个回调。预先执行这两个请求,然后使用$.when(req1,req2).done( 而不是req.done(,然后数据可以作为数组在参数中使用。
【解决方案2】:

这个例子对你有用吗?

function performTransition(){
    $('#outside').hide();
    $('#inside').html('foo');
    $('#outside').show();
}

$(function(){
    $(selector).click(performTransition);
});

【讨论】:

  • 对于给定的例子,是的。
【解决方案3】:

您可以通过标准动画队列使用.queue。它仍然很冗长,但至少没有嵌套。

$("#outside").queue(function() {
   $("#outside").hide('slow');
   $(this).dequeue();
});
$("#outside").queue(function() {
   $("#inside").html('bar');
   $(this).dequeue();
});
$("#outside").queue(function() {
   $("#outside").show();
   $(this).dequeue();
});

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 2022-09-23
    相关资源
    最近更新 更多