代码之家  ›  专栏  ›  技术社区  ›  Tomalak

jQuery:使用filter(),但同时处理两个结果

  •  13
  • Tomalak  · 技术社区  · 15 年前

    filter() 将结果减少到满足特定条件的元素。

    $("some selector").filter(function() {
      // determine result...
      return result;
    }).each( /* do something */ );
    

    但是,我又如何处理我的元素的“另一半”——但却不做与之相当的工作呢 :

    $("some selector").filter(function() {
      // determine result...
      return !result;
    }).each( /* do something else */ );
    

    基本上,我想分别喂两个人 /* do something */ 零件到单个过滤器。一个用于匹配的,另一个用于其他-无需过滤两次。我是否缺少执行此操作的jQuery函数?


    附言:我想我可以做到:

    $("some selector").each(function() {
      // determine result...
      if (result)
        /* do something */
      else
        /* do something else */
    });
    

    6 回复  |  直到 15 年前
        1
  •  16
  •   Tgr    15 年前

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

    $.fn.invert = function() {
      return this.end().not(this);
    };
    
    $('.foo').filter(':visible').hide().invert().show();
    

    invert() 不会将新元素添加到jQuery堆栈中,而是替换最后一个元素:

    $('.foo').filter(':visible').invert().end(); // this will yield $('.foo'), not $('.foo:visible')
    

    编辑: prevObject end()

        2
  •  10
  •   Kobi    15 年前

    我通常使用 not

    var all = $("some selector");
    var filtered = all.filter(function() {
      // determine result...
      return result;
    });
    var others = all.not(filtered);
    
        3
  •  1
  •   RMorrisey    15 年前

    您可以尝试编写jQuery插件来实现这一点。检查一下密码 滤波器 功能,并想出一些更准确地做你想要的。可能是这样的:

    $("some selector").processList(predicate, successCallback, failureCallback);
    

    然后您将传入三个回调:一个对对象求值以查看它是否匹配过滤器选择(您也可以接受选择器字符串等);一个处理与所选内容匹配的对象,另一个处理不匹配的对象。

        4
  •  1
  •   Tgr    15 年前
    $.fn.if = function(cond, ontrue, onfalse) {
      this.each(function() {
        if (cond.apply(this)) ontrue.apply(this);
        else onfalse.apply(this);
      });
    };
    
    $('some selector').if(function() {
      // determine result
    }, function() {
      // do something
    }, function() {
      // do something else
    });
    

        5
  •  1
  •   user113716    15 年前

    我不知道这是否更好,但是 filter() 你可以这样做:

    var $others = $();
    
    var $filtered = $('div').filter(function() {
        if(! your filter test) {
            $others.push(this);
        } else {
            return true; 
        }
    });
    
    alert($others.length);
    alert($filtered.length);
    

    一开始我试着从一个空的jQuery集开始 $() ,然后使用 add() 用非筛选结果填充它,但无法使其工作。

    编辑:

    更新为在空jQuery对象上直接使用push,如 托马拉克 .

        6
  •  0
  •   BradBrening    15 年前

    有趣的问题。我看你倾向于我的建议:

    $("some selector").each(function() { 
      if ($(this).is(SOMEFILTER)) { 
        // do something
      } else {
        // do something  
      }
      // continue with things that apply to everything
    });