Javascript / jQuery:选择包含单词的类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18074906/
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
Javascript / jQuery : Select class name that contains word
提问by vlad
How can I do this:
我怎样才能做到这一点:
I have object that has multiple classes. My goal is to get class name that has string(e.g. 'toaster') in it (or starting with that string) and put it in variable.Note that I know only the beggining of class name and I need to get whole.
我有具有多个类的对象。我的目标是获取包含字符串(例如“烤面包机”)的类名(或以该字符串开头)并将其放入变量中。注意我只知道类名的开头,我需要完整。
e.g. <div class="writer quite-good toaster-maker"></div>
例如 <div class="writer quite-good toaster-maker"></div>
I have this div as my jQuery object, I only need to put class name toaster-maker
in variable className
;
我有这个 div 作为我的 jQuery 对象,我只需要将类名toaster-maker
放在变量中className
;
Again I don't need to select object! I only need to put class name in variable.
我再次不需要选择对象!我只需要将类名放在变量中。
采纳答案by Felix Kling
So, assuming you already have a jQuery object with that div, you could get the value of the class
attribute, split the string into the class names, iterate over them and see which one contains toaster
:
因此,假设您已经有一个带有该 div 的 jQuery 对象,您可以获取该class
属性的值,将字符串拆分为类名,遍历它们并查看哪个包含toaster
:
var className = '';
$.each($element.attr('class').split(/\s+/), function(i, name) {
if (name.indexOf('toaster') > -1) { // or name.indexOf('toaster') === 0
className = name;
return false;
}
});
jQuery doesn't provide an specific function for that.
jQuery 没有为此提供特定的功能。
If you have multiple elements for which you want to extract the class names, you can use .map
:
如果您有多个要为其提取类名的元素,可以使用.map
:
var classNames = $elements.map(function() {
$.each(this.className.split(/\s+/), function(i, name) {
if (name.indexOf('toaster') > -1) { // or name.indexOf('toaster') === 0
return name;
}
});
}).get();
classNames
will then be an array of class names.
classNames
然后将是一个类名数组。
In browser which support .classList
, you could also use $.each(this.classList, ...)
instead of $.each(this.className.split(/\s+/), ...)
.
在支持 的浏览器中.classList
,您也可以使用$.each(this.classList, ...)
代替$.each(this.className.split(/\s+/), ...)
。
回答by georg
A regular expression seems to be more efficient here:
正则表达式在这里似乎更有效:
classNames = div.attr("class").match(/[\w-]*toaster[\w-]*/g)
returns all class names that contain "toaster" (or an empty array if there are none).
返回所有包含“toaster”的类名(如果没有,则返回空数组)。
回答by Ayyappan Sekar
try this,
试试这个,
var names = $('[class*=toaster]').attr('class').split(' ');
var className;
$.each(names, function(){
if (this.toLowerCase().indexOf("toaster") >= 0)
className = this;
})
console.log(className);
fiddle is here. You can also have className as an array and push the matched class names to it.
小提琴在这里。您还可以将 className 作为数组并将匹配的类名推送到它。