jQuery 的元素或类 LIKE 选择器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2220851/
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
Element or class LIKE selector for jQuery?
提问by David Andersson
For whatever reason I have these classes called .main_sub1
, .main_sub2
etc. Never mind why I can't have .main .sub
.
无论出于何种原因,我有叫这些类.main_sub1
,.main_sub2
等你别管了,为什么我不能有.main .sub
。
Is there a way with jQuery, sort of in the way it is possible to do with attributes, to get the classes containing main
?
jQuery 有没有办法,有点像处理属性的方式,来获取包含 的类main
?
回答by Tatu Ulmanen
Using $("[class^=main]")
will select all elements whose classname starts with'main'. Take a look at jQuery docs about selectors, there are a lot of other variations you can use, for example:
Using$("[class^=main]")
将选择所有类名以“main”开头的元素。看看关于 selectors 的 jQuery 文档,你可以使用很多其他的变体,例如:
[class*=main]
will select elements whose classname contains'main'[class~=main]
will select elements whose classname has the word'main' (delimited with spaces)[class$=main]
will select elements whose classname ends in'main'
[class*=main]
将选择类名包含“main”的元素[class~=main]
将选择类名包含“main”一词的元素(用空格分隔)[class$=main]
将选择类名以“main”结尾的元素
回答by Jimmy Cuadra
Yes, you can use an attribute selector to match certain values for the class
attribute.
是的,您可以使用属性选择器来匹配属性的某些值class
。
$('[class^=main]') // class begins with "main"
$('[class*=main]') // class contains "main" anywhere within it
回答by James Wiseman
In this instance, I would just treat the class attribute in the same way as you do a standard attribute.
在这种情况下,我只会像对待标准属性一样对待 class 属性。
$("[class*=main]")