2011-06-04 94 views
5

我在尋找寫作較短方式:jQuery的過濾器和相反過濾器

$('div') 
.filter(function(value) { 
    return runMyTestFunction(value); 
}) 
.hide() 
.end() 
.filter(function(value) { 
    return !runMyTestFunction(value); 
}) 
.show(); 

希望的東西沿着線:

$('div') 
.filter(function(value) { 
    return runMyTestFunction(value); 
}) 
.hide() 
.end() 
.remove(theLastWrappedSetPoppedOfftheJqueryStack) 
.show(); 

我想定義「runMyTestFunction」內聯作爲lambda表達式,因爲我認爲它會使代碼更清晰,但按照書面方式,我將不得不復制它。

回答

9

你可以這樣做:

$('div') 
.filter(runMyTestFunction); 
.hide() 
.end() 
.not(runMyTestFunction) 
.show(); 

如果你不想跑兩次方法:

$('div') 
.hide() // hide all 
.not(runMyTestFunction) 
.show(); 

或者,如果你希望隱藏只有某些元素:

var elements = $('div'); 
var toRemove = elements.filter(runMyTestFunction).hide(); 
elements.not(toRemove).show(); 
+0

我最喜歡第三種選擇。第一個仍然不讓我內聯函數沒有重複。第二個可能會產生一些閃爍的隱藏元素,然後重新顯示它們 - 可能不會,但我寧願避免它。 – 2011-06-04 17:28:45

+2

在變量中存儲是一個非常聰明的解決方案。涼! – supertrue 2012-08-21 01:00:11