我使用的是WordPress,我需要获取存储在body标记中的类名的一部分。
我想在post-type前缀之后提取单词。
<body class="post-php post-type-dissertation is-fullscreen-mode wp-embed-responsive customize-support svg">
<body class="post-php post-type-subject-imposed is-fullscreen-mode wp-embed-responsive customize-support svg">在我的示例中,我希望在dissertation前缀之后获得post-type或subject-imposed。
使用我的代码,我得到了post-type之后的所有类
var $cn = jQuery('body[class*="post-type"]').attr('class');
console.log($cn.split('post-type-')[1]);产出实例:
dissertation is-fullscreen-mode wp-embed-responsive customize-support svg如何删除所有其他类并保留dissertation或subject-imposed单词?
发布于 2021-05-31 15:09:36
var cn = jQuery('body[class*="post-type"]').attr('class');
finder = 'post-type'
my_str = ''
cn.split(' ').forEach(function(item) {
if(item.indexOf(finder) != -1){
my_str = item.split('-').splice(2, 2).join('-')
}
});
console.log(my_str)发布于 2021-05-31 14:54:42
您可以获取所有类,然后将它们拆分为数组,然后循环遍历所有类,并根据这个remove类检查它是否包含post-type。
演示代码:
var $cn = jQuery('body').attr('class').split(/\s+/); //split..
console.log("BEFORE : " + jQuery('body').attr('class'))
$($cn).each(function(i) {
//check if has value..
if ($cn[i].indexOf("post-type") < 0) {
jQuery('body').removeClass($cn[i]) //remove class...
}
})
console.log("AFTER :" + jQuery('body').attr('class').split('post-type-')[1])<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<body class="post-php post-type-dissertation is-fullscreen-mode wp-embed-responsive customize-support svg">
</body>
发布于 2021-05-31 14:57:16
您所能做的就是将所有类作为一个字符串。然后将类拆分为一个类数组。循环遍历类数组并搜索所需的文本。
jQuery(document).ready(function($) {
var body_class = $('body').attr('class');
var class_array = body_class.split(' ');
class_array.forEach(function(ele) {
if (ele.search("post-type-") != -1) {
console.log(ele);
}
});
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body class="post-php post-type-subject-imposed is-fullscreen-mode wp-embed-responsive customize-support svg">
https://stackoverflow.com/questions/67775683
复制相似问题