我有一个div id="a",可以从几个组中附加任意数量的类.每个组都有一个特定的前缀.在javascript中,我不知道该组中的哪个类在div上.我希望能够清除具有给定前缀的所有类,然后添加一个新类.如果我想删除所有以"bg"开头的类,我该怎么做?像这样的东西,但实际上有效:
$("#a").removeClass("bg*");
Run Code Online (Sandbox Code Playgroud) 我想删除类,以"颜色"开头.这些类是动态添加的,我不知道很多类以颜色开始.
<div id="sample" class="color1 orange color2 color3 blue"></div>
Run Code Online (Sandbox Code Playgroud)
jQuery的
$("#sample").removeClass("[class^='color']");
Run Code Online (Sandbox Code Playgroud)
但它不起作用.任何帮助?
当我直接指定它时,此代码段用于删除现有类,在添加新类之前(即'ratingBlock','ratingBlock1','ratingBlock2'等).但是当我在removeClass('[class ^ ="ratingBlock"]')中使用通配符选择器时,它不起作用.难道我做错了什么?谢谢.
<style type="text/css">
.ratingBlock {background:gold !important;}
.ratingBlock1, .ratingBlock2, .ratingBlock3, .ratingBlock4, .ratingBlock5 {background:LightGreen;}
</style>
<div class="test block ratingBlock">
Broken
<div><a href="#" class="ratingLink ratingNo-1">1+</a></div>
<div><a href="#" class="ratingLink ratingNo-2">2+</a></div>
<div><a href="#" class="ratingLink ratingNo-3">3+</a></div>
</div>
<script type="text/javascript">
// <![CDATA[
jQuery(document).ready(function(){
initRatingWorks();
});
function initRatingWorks() {
jQuery("a.ratingLink").bind('click', function() {
var star = jQuery(this);
var ratingBlock = star.parents('div.test.block');
var rating = star.attr('class').match(/\d+/);
if (ratingBlock.attr('class').indexOf('ratingBlock') !== -1) {
ratingBlock.removeClass('[class^="ratingBlock"]').addClass('ratingBlock' + rating);
}
else {
ratingBlock.addClass('ratingBlock' + rating);
}
return false;
});
}
// ]]>
</script>
Run Code Online (Sandbox Code Playgroud) 我需要从'layout-'中删除元素开头的所有类
我尝试:
var regex = new RegExp('\b' + 'layout-' + '.*?\b', 'g');
$(el)[0].className = $(el)[0].className.replace(regex, '');
Run Code Online (Sandbox Code Playgroud)
但它不起作用.解决方案可以在jQuery中.任何的想法?
jquery ×4
removeclass ×2
class ×1
css ×1
javascript ×1
regex ×1
removeall ×1
selector ×1
tags ×1
wildcard ×1