Is there a wildcard selector for identifiers (id)?

前端 未结 9 1621
臣服心动
臣服心动 2020-12-04 14:59

If I have an unknown amount of identifiers sharing a specific naming-scheme, is there a way to grab them all at once using jQuery?

// These are the IDs I\'d          


        
相关标签:
9条回答
  • 2020-12-04 15:44

    If you really want to match classes, not ids, the syntax is a bit more involved, since class can have multiple values.

    // handle elements like <div class="someclass1"></div>
    $('[class^="someclass"]').click(function() {
       // do stuff
    });
    
    // handle elements like <div class="foo someclass1"></div>
    $('[class*=" someclass"]').click(function() {
       // do stuff
    });
    
    0 讨论(0)
  • 2020-12-04 15:51

    Those are IDs, but you can do something similar to:

    $("[id^='instance']").click(...)
    

    That's a bit expensive though - it helps if you can specify either a) the type of element or b) a general position in the DOM, such as:

    $("#someContentDiv span[id^='instance']").click(...)
    

    The [id^='...'] selector basically means "find an element whose ID starts with this string, similar to id$= (ID ends with this string), etc.

    You can find a comprehensive list on the jQuery Docs page here.

    0 讨论(0)
  • 2020-12-04 15:55

    No need for additional expr or anything fancy if you have jQuery

    jQuery('[class*="someclass"]').click(function(){
    });
    
    jQuery('[id*="someclass"]').click(function(){
    });
    

    As noted: https://stackoverflow.com/a/2220874/2845401

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