简体   繁体   English

如何查找jQuery选择器(使用:contains)结果集的补码

[英]How to find a jQuery selector (using :contains) result set's complement

What is the best way to get the complement of a jQuery selector's result set? 补充jQuery选择器结果集的最佳方法是什么? I want to do something like the following: 我想做以下事情:

jQuery(this).find("div:contains('someValue')").show();

But I want the complement of this selection hidden: 但是我希望隐藏这种选择的补充:

jQuery(this).find("div:not(:contains('someValue'))").hide();

Is there a more elegant solution to this than just executing the complementary selector? 除了执行互补选择器之外,还有更好的解决方案吗? An alternative I can see is finding all divs first, storing the result, and filter this: 我可以看到的另一种方法是先查找所有div,存储结果,然后过滤:

var results = jQuery(this).find("div");
results.find(":contains('someValue')").show();
results.find(":not(:contains('someValue'))").hide();

But that doesn't seem that much better. 但这似乎没有更好。 Any ideas? 有任何想法吗?

var results = jQuery(this).find("div"),
    selector = ":contains('someValue')";

results.filter(selector).show();
results.not(selector).hide();

as @Simon mentioned in the comments there is a way to improve this particular solution: 正如@Simon评论中提到的,有一种方法可以改善此特定解决方案:

var results = jQuery("div", this),
    selector = ":contains('someValue')";

results.filter(selector).show();
results.not(selector).hide();

Well, I think your code is fairly good, but another option could be running this single statement: 好吧,我认为您的代码相当不错,但是另一个选择可能是运行以下语句:

jQuery(this).find("div").each(
    function() {
        var me = $(this);
        var f = me.is(":contains('someValue')") ? "show" : "hide";
        me[f]();
    }
);

Try like this, 这样尝试

jQuery(this).find("div").hide();
jQuery(this).find("div:contains('someValue')").show();
/** $.grepl 
*   uses a regular expression for text matching within an internal $.grep.
*/

$.extend({ 
 "grepl": function(el, exp){ 
  exp=new RegExp(exp,'gi'); // create RegExp
  return $( 
   this.grep( el, function(n,i){ // run internal grep
    return el[i].textContent.match(exp) != null; // match RegExp against textContent
   })
  );
 }
});

$.grepl( $('div'), '^.*someRegexp.*$' ).css('display','none'); // usage of the function

I know that this does not exactly use the ":contains" expression, but the result should be the same. 我知道这并不完全使用“:contains”表达式,但是结果应该相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM