JQuery获取元素的类名的其余部分,该字符串以字符串“whatever-”开头。

JQuery获取元素的类名的其余部分,该字符串以字符串“whatever-”开头。

问题描述:

我有js缓存名称以whatever - 开头的类,

I have js that caches classes that's name starts with "whatever-",

$('[class^="whatever-"], [class*=" whatever-"]')

但我现在想要什么要做的就是获得名称的其余部分,例如在what-9的情况下,我想得到9,我不知道该怎么做,你能帮助我吗?

but what I want now to do is get the rest of the name, for example in case of "whatever-9" I want to get "9", I don't know how to do it, can you help me?

试试这个

var check = "whatever-";         
    $('[class^="whatever-"], [class*=" whatever-"]').each(function () {    
        // Get array of class names   
        var cls = $(this).attr('class').split(' ');       
        for (var i = 0; i < cls.length; i++) {
            // Iterate over the class and log it if it matches
            if (cls[i].indexOf(check) > -1) {        
                console.log(cls[i].slice(check.length, cls[i].length));
            }       
        }    
    });

这对于超过1个班级的情况也适用。通过使用过滤器方法和一些正则表达式

This should also work for the case when there is more than 1 class. There may be cleaner ways of doing this by using filter method and a bit of regex

使用地图

var check = "whatever-";
$('[class^="whatever-"], [class*=" whatever-"]').each(function () {
    var className = this.className;

    var cls = $.map(this.className.split(' '), function (val, i) {
        if (val.indexOf(check) > -1) {
            return val.slice(check.length, val.length)
        }
    });

    console.log(cls.join(' '));
});

地图演示

Map demo