排序2行jQuery

时间:2010-05-24 04:36:13

标签: jquery jquery-ui animation sequencing

我有以下jQuery行:

// When dragging ends
stop: function(event, ui) {
    // Replace the placeholder with the original
    $placeholder.after( $this.show() ).remove();
    // Run a custom stop function specitifed in the settings
    settings.stop.apply(this);
},

我不希望settings.stop.apply(this);运行UNTIL上面的行是($placeholder.after( $this.show() ).remove();),现在正在发生的事情是settings.stop正在提前运行。

使用jQuery,我怎样才能将这两行排序,直到第一行完成为止?

2 个答案:

答案 0 :(得分:1)

动画是异步发生的,这就是为什么$this.show()未在settings.stop.apply...行之前完成的原因。所有动画都以默认(“fx”)队列结束,该队列一个接一个地播放。您可以使用the queue function向此序列添加一些内容(即使它不是动画)。所以要适应你的例子:

// When dragging ends
stop: function(event, ui) {
    // Replace the placeholder with the original
    $placeholder.after( $this.show() ).remove();
    // Run a custom stop function specitifed in the settings
    var x = this;   //make sure we're talking about the right "this"
    $this.queue(function() {
        settings.stop.apply(x);
        $(this).dequeue();    //ensure anything else in the queue keeps working
    });
},

修改以回应您的评论“您的意思是什么?”“”:

在JavaScript this can be a tricky beast中,它会根据引用的范围而变化。在传递给queue函数的回调中,this将引用正在执行queue的DOM对象(即$this引用的DOM对象。 ,外this函数中的stop完全有可能是指某个其他对象......

现在,在您的示例中,可能是外部this引用由$this jQuery对象表示的DOM对象(即您可能在某处有var $this = $(this);上面摘录这个片段的地方)。在这种情况下,x是不必要的,因为两个this将是相同的。但既然我不知道,我想我应该确定。所以,我created a closure *通过创建一个新变量x,引用了“右”thisx现在被关闭了,所以我们知道确保它引用了queue回调中的正确内容。

*这有点蠢蠢欲动,但是如果你能通过最后一篇链接的文章做到这一点,你最终会对javascript如何挂起来有一个很好的理解。

答案 1 :(得分:1)

等待动画结束的另一种方法是使用它的回调:

stop: function(event, ui) {
     $placeholder.after( $(this).show('fast', 
                           function() { // called when show is done
                              $placeholder.remove(); // var still accessable
                              settings.stop.apply(this);
                            });
                       );
相关问题