jQuery:使用过滤器(),但与两个结果 [英] jQuery: use filter(), but work with both results
问题描述
在jQuery中, filter()
会将结果减少到符合某些条件的元素。
这个分成两部分。使用元素的好一半很简单:
$ $ $(some selector)。filter(function() {
//确定结果...
返回结果;
})。each(/ * do something * /);
但是我怎样才能使用我的元素的另一半相当于:
: $(some selector)。filter(function(){
//确定结果...
return!result;
))。each(/ * do something else * /);
基本上,我想喂两个单独的 / * /
部分到一个过滤器。一个用于匹配,另一个用于其他,而不必过滤两次。我错过了一个jQuery函数吗?
PS:我想我可以这样做:
$ b $
$(some selector)。each(function(){
//判断结果...
if )
/ *做某事* /
其他
/ *做其他事情* /
});
但是我希望有更好的东西。
$。fn.invert = function(){
return this.end()。not(this);
}; $($。$ f $')。filter(':visible')。hide()。invert()。show();
注意 invert()
不会添加一个新的元素jQuery堆栈,但取代最后一个:
$ $ p $ $'$ f $'。filter(':visible 。).invert()结束(); //这将产生$('。foo'),而不是$('。foo:visible')
<在Tomalak的建议中,将 prevObject
更改为 end()
。 >
In jQuery, filter()
reduces your result to those elements that fulfill a certain condition.
This splits the list in two parts. Working with the "good half" of the elements is easy:
$("some selector").filter(function() {
// determine result...
return result;
}).each( /* do something */ );
But how can I work with the "other half" of my elements, too - but without doing the equivalent of this:
$("some selector").filter(function() {
// determine result...
return !result;
}).each( /* do something else */ );
Basically, I'd like to feed two separate /* do something */
parts to a single filter. One for those that match, and one for the others - without having to filter twice. Am I missing a jQuery function that does this?
P.S.: I guess I could do:
$("some selector").each(function() {
// determine result...
if (result)
/* do something */
else
/* do something else */
});
But I was hoping for something nicer.
The method recommended by Kobi in plugin form:
$.fn.invert = function() {
return this.end().not(this);
};
$('.foo').filter(':visible').hide().invert().show();
Note that invert()
will not add a new element to the jQuery stack but replace the last one:
$('.foo').filter(':visible').invert().end(); // this will yield $('.foo'), not $('.foo:visible')
Edit: changed prevObject
to end()
at Tomalak's suggestion.
这篇关于jQuery:使用过滤器(),但与两个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!