2009-12-02 79 views
0

我想加快jQuery的性能。我發現本網站上的一些問題/解答幫助,但我試圖把它更進了一步......緩存複雜的jquery選擇器基於父&類型

這裏的HTML,相當簡化

<div id="Container"> 
    <div> 
     <div> 
      <input type="text" id="something"> 
     </div> 
     <input type="text" id="other"> 
    </div> 
</div> 

現在我的jQuery的例子..

// select all input text boxes inside the div with ID "Container" 
var allInputText = $("#Container input:text"); 

// the inner workings of these have been removed... 
allInputText.change().bind(); 

// Now I have 10+ class checks where I run a function on them... 
$(".numeric").numeric(); 
// ... 
$(".etc").etc(); 

目標是提高這10+級別檢查的速度。它們都是div「Container」中的相同文本框,只是指定了不同的類。它的工作原理,如果我這樣做:

$(".numeric", allInputText); 

理想情況下,我想用「allInputText」,因爲真的我只是在尋找:

var myContainer = document.getElementById("Container"); 
$(".numeric", myContainer).numeric(); 

但如果我這樣做不工作對於Container div中輸入文本框上的「.numeric」類。這被緩存在正上方以執行change()和bind(),但現在我想在這些方面做更多的事情,除了不同的類的不同事情。任何想法如何實現最佳的緩存性能?

回答

2

既然你有一組元素,你需要過濾集合,而不是在你的代碼正在做的集合中找到。

嘗試allInputText.filter(".numeric")

+0

Ahh filter!這就是我所錯過的。非常感謝,這削減了數百毫秒。 – macca1 2009-12-02 23:35:19