jQuery:使用 filter(),但同时处理两个结果 [英] jQuery: use filter(), but work with both results

查看:17
本文介绍了jQuery:使用 filter(),但同时处理两个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 jQuery 中,filter() 将您的结果缩减为满足特定条件的那些元素.

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 */ );

基本上,我想将两个单独的 /* do something */ 部分提供给单个过滤器.一种用于匹配的,另一种用于其他 - 无需过滤两次.我是否缺少执行此操作的 jQuery 函数?

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.:我想我可以做到:

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.

推荐答案

Kobi推荐的插件形式的方法:

The method recommended by Kobi in plugin form:

$.fn.invert = function() {
  return this.end().not(this);
};

$('.foo').filter(':visible').hide().invert().show();

请注意,invert() 不会向 jQuery 堆栈添加新元素,而是替换最后一个:

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')

在 Tomalak 的建议下将 prevObject 更改为 end().

changed prevObject to end() at Tomalak's suggestion.

这篇关于jQuery:使用 filter(),但同时处理两个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆