hasClass()以字符串开头 [英] hasClass() starts with string
问题描述
是否可以以及如何使用hasClass()
,以便我可以搜索以某些指定的字符串开头的类?
我想查看多个类,以查看是否存在至少一个以字符串开头的类.
Is it possible and how do I use hasClass()
so that I can search for classes that start with some specified string?
I want to look at multiple classes to see if there exists at least one class that starts with a string.
string: "old"
这有可能吗,您还可以进行包含或通配符搜索吗?
Is this possible and are you also able to do contains or wildcard searching?
推荐答案
选择器将是:[class^=old]
因此:
$('[class^=old]')
语法:
-
[attr^=vvv]
=>选择所有具有属性attr
的元素,其值以vvv
开头.Syntax :
[attr^=vvv]
=> Select all elements have attributeattr
,its value starts withvvv
.[attr$=vvv]
=>选择所有具有属性attr
的元素,其值以vvv
结尾.[attr$=vvv]
=> Select all elements have attributeattr
,its value ends withvvv
.[attr*=vvv]
=>选择所有具有属性attr
的元素,其值包含vvv
.[attr*=vvv]
=> Select all elements have attributeattr
,its value containsvvv
.对于您而言,
is
方法比hasClass
更合适:In your case ,
is
method is suitable more thanhasClass
:if (element.is('[class^=old]')){ }
不是
if (element.hasClass('[class^=old]')){ }
JQuery插件:
$.fn.hasClassStartsWith=function(prefix){ return $(this).is(`[class^=${prefix}]`); };
然后:
if (element.hasClassStartsWith('old')){ // do your staff }
这篇关于hasClass()以字符串开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!