jQuery: use filter(), but work with both results

后端 未结 6 1818
孤城傲影
孤城傲影 2021-01-01 23:16

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

6条回答
  •  执念已碎
    2021-01-01 23:40

    I don't know if this is any nicer, but using filter() you could do something like:

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

    EDIT:

    At first I tried it starting with an empty jQuery set $(), and then using add() to populate it with the non-filter results, but couldn't make it work.

    EDIT:

    Updated to use push directly on an empty jQuery object as suggested by Tomalak.

提交回复
热议问题