jQuery方法来选择一个子集,以及它的反函数吗? [英] jQuery method to select a subset and also its inverse?

查看:76
本文介绍了jQuery方法来选择一个子集,以及它的反函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一些jQuery对象集以及该对象集的子集,是否有一种方法可以返回 inverse 子集?

Given some jQuery object set, and also a subset of that set, is there a method that will return the inverse subset?

如果答案是"",有什么方法可以避免进行第二选择以获得逆子集?

If the answer is "No", is there any way to avoid making a second selection to get the inverse subset?

说明性示例:

<ul>
  <li class="subset"></li>
  <li class="subset"></li>
  <li class="inverse"></li>
  <li class="inverse"></li>
</ul>

首先,我想对所有<li>做某事,然后对仅.subset做某事,最后对仅.inverse做其他事:

First I want to do something to all the <li>, then something to only .subset, and finally something else to only .inverse:

$('li').css('background-color','blue')
  .filter('.subset')
    .css('color','black')
  .inverse()  // <-- White Whale?!?
    .css('color','white');

我知道使用.end().filter('.inverse')可以很容易地做到这一点,但是假设选择器实际上很大讨厌,并且运行两次将是很大的性能击.那怎么办?

I know this could be easily done with .end().filter('.inverse'), but suppose the selector were actually big and nasty and running it twice would be a big performance hit. What then?

在API文档中还没有找到类似的东西,但是我是jQuery的新手,可能已经忽略了一些显而易见的东西(而且,.andSelf()的存在意味着这不会不合理...).

Haven't found anything like this in the API docs, but I'm new to jQuery and may have overlooked something obvious (also, the existence of .andSelf() means this would not be unreasonable to expect...).

推荐答案

没有内置函数,反向过滤器是您所追求的...替代方法不可链接.替代方法是 .not() ,如下所示:

There's no built-in function for this, the reverse filter is what you're after...the alternative isn't chainable. The alternative would be .not(), like this:

var all = $('li').css('background-color','blue');
var sub = all.filter('.subset').css('color','black');
all.not(sub).css('color','white');

...但同样也不是很漂亮,我会坚持使用.end().filter()方法.但是,如果性能至关重要,请使用上面的 .not() 方法,它会更高效(因为没有选择器针对逆集合运行.

...but again it's not pretty, I'd stick with the .end().filter() approach. However, if performance is paramount, use the .not() approach above, it is more efficient (since no selector runs for the inverse set).

对于您的特定示例(尽管不是一般性问题),这样做很快:

For your specific example (though not the general question), it'd be pretty quick to do this:

$('li').css('background-color','blue').css('color','white')
       .filter('.subset').css('color','black');

这篇关于jQuery方法来选择一个子集,以及它的反函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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