Is there a wildcard selector for identifiers (id)?

2019-01-13 04:05发布

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 like to select
#instance1
#instance2
#instance3
#instance4

// What do I need to add or how do I need to modify this jQuery selector in order to select all the IDs above?
("#instanceWILDCARD").click(function(){}

9条回答
别忘想泡老子
2楼-- · 2019-01-13 04:30

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
});
查看更多
老娘就宠你
3楼-- · 2019-01-13 04:36

Use the carrot.

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

jsFiddle example

查看更多
倾城 Initia
4楼-- · 2019-01-13 04:38

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
});
查看更多
家丑人穷心不美
5楼-- · 2019-01-13 04:40

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!

查看更多
叼着烟拽天下
6楼-- · 2019-01-13 04:43

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

查看更多
beautiful°
7楼-- · 2019-01-13 04:46

We can do it this way:

$(document).ready(function () {
    $('[id*=btnOk]').live("click", function () {

    });
});
查看更多
登录 后发表回答