jQuery method to select a subset and also its inverse?

前端 未结 2 390
说谎
说谎 2021-01-20 11:33

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

2条回答
  •  [愿得一人]
    2021-01-20 11:42

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

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

提交回复
热议问题