HTML
<div class="ativo37 and many other classes"></div>
<div class="another classes here with ativo1"></div>
<div class="here ativo9 and more two or three"></div>
Run Code Online (Sandbox Code Playgroud)
JS
$("div[class^='ativo']").on("click", function(){
$(this).removeClass("^='ativo'"); // How to achieve it?
});
Run Code Online (Sandbox Code Playgroud)
我该怎么做而不是.removeClass("^='ativo'");?
Mil*_*war 16
.removeClass() 接受一个删除类的函数,并接受索引和旧的CSS值:
一个函数,返回一个或多个要删除的空格分隔的类名.接收集合中元素的索引位置和旧类值作为参数.
您可以删除以所需名称开头的类名,并使用以下内容保留现有名称:
$("div[class*='ativo']").removeClass (function (index, css) {
return (css.match (/(^|\s)ativo\S+/g) || []).join(' ');
});
Run Code Online (Sandbox Code Playgroud)
voi*_*oid 15
function removeClassByPrefix(el, prefix) {
var regx = new RegExp('\\b' + prefix + '.*?\\b', 'g');
el.className = el.className.replace(regx, '');
return el;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用此纯Javascript解决方案.
没有jQuery,您可以使用classList和startsWith:
var el = document.querySelector('div[class^="ativo"]');
el.classList.forEach(className => {
if (className.startsWith('ativo')) {
el.classList.remove(className);
}
});
Run Code Online (Sandbox Code Playgroud)