javascript 使用通配符选择类而不是确切的类名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5111272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 15:58:35  来源:igfitidea点击:

selecting classes using wildcard not exact class name

javascriptjquery

提问by twitter

I have several classes that I want to select .group1-1 .group1-2 .group1-3, each one of these has 50 elements under it.

我有几个类要选择 .group1-1 .group1-2 .group1-3,每个类下面都有 50 个元素。

Is there a way to select all classes that start with group1 (so I end up selecting group1-1, group1-2, group1-3), something like $(".group1"+*)

有没有办法选择所有以 group1 开头的类(所以我最终选择了 group1-1、group1-2、group1-3),比如 $(".group1"+*)

回答by iwasrobbed

You can also use something along the lines of this if you'd like to avoid regex:

如果你想避免使用正则表达式,你也可以使用类似的东西:

$("[class^='group1-']").click(function () {
    var groupNumber = $(this).attr('class').split('-')[1];
    alert('Yep, you clicked group1-' + groupNumber); 
});

Example here: http://jsfiddle.net/iwasrobbed/7bjtb/

这里的例子:http: //jsfiddle.net/iwasrobbed/7bjtb/

回答by John Weldon

This questiondiscusses jquery wildcard / regex selectors. Which basically allow you to use a regular expression to specify matching classes.

这个问题讨论了 jquery 通配符/正则表达式选择器。这基本上允许您使用正则表达式来指定匹配的类。