jQuery: Wildcard class selector in removeClass

后端 未结 4 1088
情书的邮戳
情书的邮戳 2020-12-21 09:46

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

相关标签:
4条回答
  • 2020-12-21 10:04

    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/

    0 讨论(0)
  • 2020-12-21 10:19

    $.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');
    
    0 讨论(0)
  • 2020-12-21 10:27

    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

    0 讨论(0)
  • 2020-12-21 10:29

    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

    0 讨论(0)
提交回复
热议问题