如何检查CSS类中是否存在子字符串并将其删除? [英] How to check if substring exists in CSS Class and remove it?
问题描述
我们有几个具有以下模式的CSS类.它们都以bg--
或color--
开头.如何使用jQuery
检查元素是否包含CSS类子字符串,如果找到,则将其删除?
We have several CSS classes with the following pattern below. They all start with either bg--
or color--
. How can I check if an element contains the CSS class substring using jQuery
and if found then remove it?
示例:
-
bg--white
-
bg--red
-
bg--orange
-
color--orange
-
color--red
-
color--purple
bg--white
bg--red
bg--orange
color--orange
color--red
color--purple
我尝试过的
$(function() {
var divEl = $('div');
if(divEl.hasClass('*=bkg--') {
divEl.removeClass('*=bkg--');
}
if(divEl.hasClass('*=color--') {
divEl.removeClass('*=color--');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bkg--red color--white">Holisticly build resource sucking methodologies before distributed methodologies. </div>
<div class="bkg--orange color--white">Phosfluorescently integrate revolutionary collaboration and idea-sharing through efficient services.</div>
<div class="bkg--purple color--purple">Credibly maximize impactful e-tailers with resource-leveling convergence. </div>
推荐答案
您可以访问所需的.prop()
(在您的情况下为"class"
)并使用JS的 String.prototype.replace()
You can access the desired .prop()
("class"
in your case) and change it on the fly using JS's String.prototype.replace()
$("div").prop("class", function( i, cls ) {
console.log("Before: "+ cls )
cls = cls.replace(/(^|\s)(bg|color)--\S+/g, '');
console.log("After: "+ cls )
return cls;
});
.bg--white {background: white;}
.bg--red {background: red;}
.bg--orange {background: orange;}
.color--orange {color: orange;}
.color--red {color: red;}
.color--purple {color: purple;}
<div class="test bg--red color--white">Holisticly</div>
<div class="foo--bar bg--orange color--white">Phosfluorescently</div>
<div class="bg--purple color--purple">Credibly</div>
<script src="//code.jquery.com/jquery-3.1.0.js"></script>
或者简单地:
$("div").prop("class", function( i, cls ) {
return cls.replace(/(^|\s)(bg|color)--\S+/g, '');
});
或者如果您使用JS编译器(例如Babel.js)
Or if you use a JS compiler (like i.e: Babel.js)
$("div").prop("class", (i, c) => c.replace(/(^|\s)(bg|color)--\S+/g, ''));
此外,您可以将选择器更改为:
Additionally, instead of using the too general $("div")
you can instead change your selector to:
$("[class^='bg--'], [class*=' bg--'], [class^='color--'], [class*=' color--']")
虽然有点长,但是可以很好地完成工作.
It's a bit long but it does the job perfectly fine.
这篇关于如何检查CSS类中是否存在子字符串并将其删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!