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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:03:04  来源:igfitidea点击:

Element or class LIKE selector for jQuery?

jqueryjquery-selectorssql-like

提问by David Andersson

For whatever reason I have these classes called .main_sub1, .main_sub2etc. 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 classattribute.

是的,您可以使用属性选择器来匹配属性的某些值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]")