A cleaner way to select by multiple possible attribute values?

后端 未结 2 1815
甜味超标
甜味超标 2020-11-29 11:11

Is there a possibility in jQuery to select by multiple possible attribute values without having to use a comma separated list of selectors.

So in stead of:



        
相关标签:
2条回答
  • 2020-11-29 11:48

    Not that I know of. The cleanest way I can think of doing this is to first select using the common elements across all items, then just .find() or .filter() the OR values out.

    Something like

    $('#list1 > option[value]')
        .filter('[value="1"],[value="2"]')
        ;
    
    0 讨论(0)
  • 2020-11-29 11:49

    You can make a custom jQuery function like this:

    $.fn.filterAttrVals = function (attr, vals) {
        var filter = '[' + attr + '="' + vals.split(',').join('"],[' + attr + '="') + '"]';
        return this.filter(filter);
    };
    

    For your example you could use it in the following way:

    $('#list1 > option').filterAttrVals('value','1,2');
    
    0 讨论(0)
提交回复
热议问题