jQuery - multiple :not selector

前端 未结 3 2204
旧巷少年郎
旧巷少年郎 2020-12-05 09:28

I\'m trying to target page-wide links that do not start with a \'#\' and do not include in-line javascript but I\'m having problems figuring out how to structure the selecto

3条回答
  •  醉话见心
    2020-12-05 09:46

    As indicated in jQuery - Multiple Selectors in a :not()? , this is the correct way to do this:

    $( 'a:not([href*=javascript],[href^=#])' )
    

    Don't forget to put quotes around commas if you already already have your selectors to negate in variables

    var selOne = '[href*=javascript]';
    var selTwo = '[href^=#]';
    $('a:not(' + selOne + ',' + selTwo + ')')
    

    I admit that the code gets a bit confusing but it has an advantage, you can do things such as this:

    var selOne = '[href*=javascript], [href^=#]';
    var selTwo = '.anotherSelector, .andAnother, .andSoOn';
    $('a:not(' + selOne + ',' + selTwo + ')')
    

    It's useful whenever you need to group selectors for some reason, ie. using the same group of selectors somewhere else in the code.


    A live example using the same technic

    $('div:not(.rose-flower,.bus-vehicle)').css('color','red');
    
    
    I am a bus
    I am a strawberry
    I am a rose

    Also on http://jsfiddle.net/bmL8gz5j/


    :not vs .not(): For performance reasons, you should use :not rather than .not(), see Performance differences between using ":not" and ".not()" selectors?

提交回复
热议问题