当前位置 : 主页 > 网页制作 > JQuery >

jQuery:removeClass中的通配符类选择器

来源:互联网 收集:自由互联 发布时间:2021-06-15
当我直接指定现有类(即,ratingBlock’,’ratingBlock1′,’ratingBlock2’等)时,此代码段会在添加新类之前删除现有类.但是当我在removeClass(‘[class ^ =“ratingBlock”]’)中使用通配符选择器时,它不
当我直接指定现有类(即,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>
$.removeClass()不将选择器作为参数,只接受类名(或类名).

见:Removing multiple classes (jQuery)

所以你基本上需要打电话:

$.removeClass('ratingBlock1 ratingBlock2 ratingBlock3 ratingBlock4 ratingBlock5');
网友评论