2012-08-23 38 views
0

首先,我很抱歉。我知道我想做什麼,但不知道我應該怎麼稱呼它,或者怎麼問它,所以我的谷歌搜索是無用的。讓jQuery使用DOM元素作爲對象?

我有一些動畫用於顯示/隱藏文本。我試圖把它包裝在一個對象中,但是我這樣做的方式是,我必須每次運行一些計算代碼,因爲我不知道它將與哪個部分一起存儲。

現在,我討厭的是,我在每一遍都重新運行calculatePositions(entry);函數,而不是使用保存的值。麻煩的是,這會發生在多個元素上,所以位置數組需要改變。有沒有辦法將位置數組保存到特定的DOM元素並只計算一次?我可以將這些函數和屬性附加到DOM元素,而不是每次都傳遞entry對象嗎?

我的代碼:

var theShort = {}; 

theShort.toggle = function(){ 
    var positions = new Array; 

    function calculatePositions(entry){ 
     /* 
     positions = Nasty calculation code 
     */ 
    } 

    function showLong(entry){ 
     calculatePositions(entry); 
     //My toggle code is obviously more complex and uses the positions array. 
     //But for simplicity sake, I've omitted it 
     $(entry).find('.tsl-theshort').show(); 
     $(entry).find('.tsl-thelong').hide(); 
    } 

    function showShort(entry){ 
     calculatePositions(entry); 
     $(entry).find('.tsl-theshort').show(); 
     $(entry).find('.tsl-thelong').hide(); 
    } 

    return { 
     init: function(){ 
      $('.tsl-showLong').click(function(){ 
       showLong($(this).closest('.entry-content')); 
       return false; 
      }); 

      $('.tsl-showShort').click(function(){ 
       showShort($(this).closest('.entry-content')); 
       return false; 
      }); 
     } 
    }; 
}(); 

jQuery(document).ready(function($){ 
    theShort.toggle.init(); 
}); 
+0

無關,但'VAR位置=新數組;'應該是'var positions = [];' – jbabey

回答

0

如果你擔心每次運行的計算功能,建立了基於元素的ID的高速緩存。如果每個元素都有DOM中的唯一的ID,你可以不喜歡

var cache = {}; 

function showLong(entry){ 
    var id = $(entry).attr('id'); 
    if(!cache[id]) 
     cache[id] = calculatePositions(entry); 

    //My toggle code is obviously more complex and uses the positions array. 
    //But for simplicity sake, I've omitted it 
    $(entry).find('.tsl-theshort').show(); 
    $(entry).find('.tsl-thelong').hide(); 
} 

function showShort(entry){ 
    var id = $(entry).attr('id'); 
    if(!cache[id]) 
     cache[id] = calculatePositions(entry); 

    $(entry).find('.tsl-theshort').show(); 
    $(entry).find('.tsl-thelong').hide(); 
} 

然後,當你想查找一個元素的計算,

var id = $(element).attr('id'); 
var calculation = cache[id];