2011-06-04 32 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