1

目前我已经这样设置了,

var elements = $('#one, $two, #three, #four, #six');

var _temp = 0;
elements.hide(0, function(){
    /* by default, the callback will be performed to
       every single element in stack */

    _temp++; // increment temporary cache

    // perform actual callback only on last in list
    if (_temp == elements.length) {
        // do stuff
    }
});

但感觉不对,因为如果我想对下面的另一个回调 241 行做同样的事情,我必须重置_temp,而且,全局变量只是混乱。

我怎么能简化这个?

4

3 回答 3

3

一种可能的方法是使用闭包:

var elements = $('#one, $two, #three, #four, #six');

elements.hide(0, (function(){
    var _temp = 0;
    return function(){
        _temp++; // increment temporary cache

        // perform actual callback only on last in list
        if (_temp == elements.length) {
            // do stuff
        }
    };
})());

如果您想更频繁地使用此模式,您可以创建一个返回回调的函数。

另请注意,.hide()有一个持续时间作为第一个参数。

于 2012-07-18T07:55:00.900 回答
1

尝试在函数中使用静态变量。

于 2012-07-18T07:59:05.063 回答
0

还有另一种没有临时变量的方法,它可能对某些人来说可读性较差,并迫使您将选择存储在变量中,但是:

elements.hide(0, function(){
    // if last callback (compare raw DOMElements, because jQuery object aren't somehow similar)
    if ($(this)[0] === elements.last()[0]) {
        // do stuff
    }
});

缩小一些线,并做到了。

于 2012-07-18T08:16:48.197 回答