How can I select an element by ID with jQuery using regex?

前端 未结 7 1634
执念已碎
执念已碎 2020-11-28 05:51

I have the following input elements:




        
相关标签:
7条回答
  • 2020-11-28 06:26

    You can look for id's starting with AAA and ending with BBB like this:

    ​$("[id^=AAA_][id$=_BBB]")
    

    The working fiddle: http://jsfiddle.net/DN9uV/

    0 讨论(0)
  • 2020-11-28 06:36

    Use this:

    $('[id^="AAA_"][id$="_BBB"]')
    

    Fiddle: http://jsfiddle.net/J6hGx/

    0 讨论(0)
  • 2020-11-28 06:37

    You can combine both selectors in a multiple attribute selector.

    ​$("[id^=AAA_][id$=_BBB]")
    

    It will return all the elements that matches all the specified attribute filters:

    • [id^=AAA_] matches elements with id attribute starting with AAA_, and
    • [id$=_BBB] matches elements with id attribute ending with _BBB.

    Another generic alternatives:

    • Using a custom :regex() selector,
    • Using a .filter()-based approach.
    0 讨论(0)
  • 2020-11-28 06:37

    It would be better to just check for the id ending on _BBB by

     $("[id$=_BBB]")
    
    0 讨论(0)
  • 2020-11-28 06:37

    I use to solve this with the class selectors which don't need to be unique.

    This also has a positive effect on speed because no complex search is required Additionally you can use this for the different styling of different elements

    e.g.

    <elem id="1" class="aa">element type aa</elem>
    <elem id="2" class="aa">element type aa</elem>
    <elem id="3" class="aa bb">element type aa and bb</elem>
    <elem id="4" class="bb">element type bb</elem>
    

    Now you can simply use the class selector

    $('.aa').click(function(){
         console.log( 'clicked type aa #' + $(this).attr('id') );
    });
    
    $('.bb').click(function(){
         console.log( 'clicked type bb #' + $(this).attr('id') );
    });
    
    0 讨论(0)
  • 2020-11-28 06:49

    This can be done like so:

    $('input').filter(function(){ return this.id.match(/^AAA_.+_BBB$/) })
    

    You can give use $('input', <context>) to make the search more precise. See also here

    0 讨论(0)
提交回复
热议问题