本文介绍了jQuery:removeClass中的通配符类选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我直接指定一个新类(即"ratingBlock","ratingBlock1","ratingBlock2"等)时,此代码片段可在添加新类之前删除现有类.但是,当我在removeClass('[class ^ ="ratingBlock"]')中使用通配符选择器时,它不起作用.难道我做错了什么?谢谢.
This code snippet works to remove an existing class, before adding a new one, when I specify it directly (ie, 'ratingBlock', 'ratingBlock1', 'ratingBlock2', etc.). But when I use a wildcard selector in the removeClass ('[class^="ratingBlock"]'), it doesn't work. Am I doing something wrong? Thanks.
<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>
推荐答案
$.removeClass()
不将选择器作为参数,而仅将类名(或类名)作为参数.
$.removeClass()
doesn't take a selector as a parameter, only a class name (or class names).
请参阅:删除多个类(jQuery)
因此,您绝对需要致电:
So you basiacally need to call:
$.removeClass('ratingBlock1 ratingBlock2 ratingBlock3 ratingBlock4 ratingBlock5');
这篇关于jQuery:removeClass中的通配符类选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!