问题
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>
回答1:
$.removeClass()
doesn't take a selector as a parameter, only a class name (or class names).
See: Removing multiple classes (jQuery)
So you basiacally need to call:
$.removeClass('ratingBlock1 ratingBlock2 ratingBlock3 ratingBlock4 ratingBlock5');
回答2:
removeClass
takes either a function or a class name. You are trying to provide a css selector. It looks like all you need is:
ratingBlock.removeClass('ratingBlock').addClass('ratingBlock' + rating)
Furthermore you could remove a wildcard like this:
ratingBlock.removeClass (function (index, css) {
return (css.match (/ratingBlock/g) || []).join(' ');
});
Reference: JQuery removeClass wildcard
回答3:
If it makes it any easier, I wrote a plugin for another answer that will strip classes beginning (or ending) with a match, so
ratingBlock.stripClass('ratingBlock-').addClass('ratingBlock-' + rating);
will remove ratingBlock-1
and ratingBlock-2
but not ratingBlock
(as long as you include the dash).
Code: https://gist.github.com/zaus/6734731
回答4:
I think your problem is the quotation marks: I don't think you need them, try omitting them.
'[class^=ratingBlock]'
EDIT:
.removeClass()
accepts a class name, not a selector.
You can, however, specify multiple space separated class names, so could try this:
.removeClass('ratingBlock ratingBlock1 ratingBlock2');
http://api.jquery.com/removeClass/
来源:https://stackoverflow.com/questions/16039708/jquery-wildcard-class-selector-in-removeclass