<body class="some-class xxx-term-i-want-to-extract some-other-class">
如何从身体类中提取“term-i-want-to-extract”,知道这总是以“xxx - ”开头?
编辑:问题是关于获取“term-i-want-to-extract”并将其存储在变量中。不是将它从body类中删除或者在没有它的情况下返回body类。谢谢你的回答!
答案 0 :(得分:2)
您可以使用classList
获取body
标记所包含的所有类的列表,然后使用$.map
函数覆盖它们并仅返回相关的类(删除xxx-
字符串后。)
var classes = $.map($('body')[0].classList, function(cls, i) {
if (cls.indexOf('xxx-') === 0) {
return cls.replace('xxx-', '');
}
})
console.log(classes);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="some-class xxx-term-i-want-to-extract some-other-class">
&#13;
答案 1 :(得分:0)
// get the jQuery element
var $body = $('body');
// get the contents of the `class` attribute
// and use String#split to divide it into an
// array of individual class strings
var classes = $body.attr('class').split(' ');
// Array#find is used to find the first class
// that starts with the selected pattern
// and then the pattern is sliced off of the
// full class string
var xxx = classes.find(function (className) {
return className.startsWith('xxx-');
}).slice(4);
xxx === 'term-i-want-to-extract'; // true
Array#find
和String#startsWith
是ES2015规范的一部分,因此可能无法在所有平台上使用。然后,您可能需要在IE等旧版浏览器中使用polyfill: