简体   繁体   English

获取具有多个类的元素的特定类名

[英]getting a specific class name of an element with multiple classes

Lets say I have this in my html: 可以说我的html中有这个:

<div id="myDiv" class="a b-32"/>

I'm trying to get the index of 'b' class (in my example '32') 我正在尝试获取“ b”类的索引(在我的示例中为“ 32”)

The only way I know how to do it is by: 我知道怎么做的唯一方法是:

var index;
var myDiv = $("#myDiv").attr("class");
var classes = myDiv.split(' ');
for(var i=0; i<classes.size(); i++){
    if(classes[i].matches((b-)+[\d]*) ){
        index = classes[i].replace("b-","");
    }
}
alert(index);

Is there any solution that doesn't imply iterating all the classes manually? 有没有解决方案不意味着手动迭代所有类? Because my solution seems dull. 因为我的解决方案似乎很乏味。 Surely there must be a better way, I just can't find it. 当然,必须有更好的方法,我只是找不到。

Y'know, for all that people claim jQuery makes it so you have to write less code, Vanilla JS is surprisingly good at one-liners :p 知道,尽管人们声称jQuery做到了这一点,所以您不必编写更少的代码,但Vanilla JS擅长于单行代码:p

alert((document.getElementById('myDiv').className
                                         .match(/(?:^| )b-(\d+)/) || [0,0])[1]);

(Whitespace added for readability) (添加了空格以提高可读性)

Returns 0 in the event where myDiv doesn't have a b-number class. 如果myDiv没有b-number类,则返回0

EDIT: As @A.Wolff pointed out in a comment on your question, you may wish to consider this: 编辑:正如@ A.Wolff在对您的问题的评论中指出的那样,您不妨考虑一下:

<div id="myDiv" class="a" data-b="32"></div>

Then you can get: 然后您可以获得:

alert(document.getElementById('myDiv').getAttribute("data-b"));

A regular expression can help: 正则表达式可以帮助:

var index;
var myDivClasses = $("#myDiv").attr("class");
var cls = myDivClasses.match(/(?:^| )b-(\d+)(?:$| )/);
if (cls) {
    index = cls[1];
}

(Use parseInt if you want it as a number.) (如果需要,请使用parseInt作为数字。)

That looks for b-### where ### is one or more digits, with either whitespace or a boundary (start of string, end of string) on either side, and extracts the digits. 查找b-### ,其中###是一个或多个数字,在任一侧带有空格或边界(字符串的开头,字符串的结尾),并提取数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM