Is there a wildcard selector for identifiers (id)?

前端 未结 9 1620
臣服心动
臣服心动 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:35

    The attribute starts-with selector ('^=) will work for your IDs, like this:

    $("[id^=instance]").click(function() {
      //do stuff
    });
    

    However, consider giving your elements a common class, for instance (I crack myself up) .instance, and use that selector:

    $(".instance").click(function() {
      //do stuff
    });
    
    0 讨论(0)
  • 2020-12-04 15:35

    Use the carrot.

    $("div[id^=instance]").hide();
    

    jsFiddle example

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

    I'm surprised no one has mentioned creating your own filter selector (by extending jQuery's Selector functionality). Here I've created a wildcard selectors I called "likeClass" and "likeId" that accepts any wildcard string and will find all elements that are a match (similar to Regex matching).

    Code:

    $.expr[':'].likeClass = function(match){
          return $('[class*=" '+ match +'"]');
    };
    $.expr[':'].likeId = function(match){
          return $('[id*=" '+ match +'"]');
    };
    

    Example Usage:

    Now let's say you had multiple div elements with similar names like .content-1, .content-2, .content-n... etc and you want to select them. Now it's cake!

    $('div:likeClass(content-)'); // Returns all elements that have a similar Classname: content-*

    or

    $('div:likeClass(content-)'); // Returns all elements that have a similar ID: content-*

    Oh yeah, one more thing... you can chain it too. :)

    $('li:likeId(slider-content-)').hide().addClass('sliderBlock').first().fadeIn('fast');
    

    Enjoy!

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

    Why don't you just assign class = "instance" to all of them and select them using $('.instance')?

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

    We can do it this way:

    $(document).ready(function () {
        $('[id*=btnOk]').live("click", function () {
    
        });
    });
    
    0 讨论(0)
  • 2020-12-04 15:43

    This is the only correct answer to the id wildcard question.

    $('[id*="Wild card in double quotes"]') 
    

    This will get "Wild card in double quotes. And there's more!!!", and also "More BS in front of Wild. Wild card in double quotes".

    You should use quote marks that are different than your '[]' tags.

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