本文介绍了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
这篇关于JQuery获取元素的类名的其余部分,该字符串以字符串“whatever-”开头。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!