2012-07-18 40 views
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,而且,全局變量只是一團糟。

我怎麼能簡化這個?

+0

'hide'沒有回調作爲第一個參數。這沒有任何意義。 – VisioN 2012-07-18 07:55:34

+0

Woops,是不是從腳本複製粘貼,忘記了0. – jolt 2012-07-18 08:04:04

回答

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()的持續時間爲第一個參數。

+0

啊,總是關閉。 :( – jolt 2012-07-18 08:07:28

+0

它總是*是關閉 – 2012-07-18 08:07:47

+1

雖然,我可以建議,如果相同的回調將在文檔中的其他地方使用,那麼緩存自我調用函數的返回函數可能更合適,然後將它傳遞給'elements.hide()'而不是 – 2012-07-18 08:09:33

1

嘗試在你的函數中使用一個靜態變量。

+1

你的聲明應該是一個註釋,但不是答案 – VisioN 2012-07-18 07:59:55

+0

對不起,這是我第一次,我甚至不確定那是什麼語言 – Chefire 2012-07-18 08:03:33

+0

而且我是試圖獲得15點聲望才能給答案+1。 – Chefire 2012-07-18 08:04:13

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

縮小了一些線路,並執行訣竅。