jQuery - Remove all classes with similar names

后端 未结 4 1711
攒了一身酷
攒了一身酷 2021-01-02 07:10

Is there any better way to do this?

$(\'element\').removeClass(\'class-1\').removeClass(\'class-2\').removeClass(\'class-3\').removeClass(\'class-5\') ...
to         


        
相关标签:
4条回答
  • 2021-01-02 07:30

    Doing it in a better way using css selector, [type*=value]

    $(function() {
        var i = 0;
        while( ++i <= 105) {
            $('b').addClass('class-'+ i);
        }
      var clas = '';
      var arey =[]
        $('input[type=button]').click(function() {  
            clas = $('b').attr('class');
            arey = clas.match(/class-\d{1,3}/g);
            $.each(arey, function(i, e) {
                $('b').removeClass(e);      
            });
        });
    }); 
    

    Edit :

    Demo : http://jsbin.com/opebu4/2

    0 讨论(0)
  • 2021-01-02 07:34

    Here's a small jQuery plugin I'm using for this purpose:

    (function($) {
        $.fn.removeClassWild = function(mask) {
            return this.removeClass(function(index, cls) {
                var re = mask.replace(/\*/g, '\\S+');
                return (cls.match(new RegExp('\\b' + re + '', 'g')) || []).join(' ');
            });
        };
    })(jQuery);
    

    You use it like this:

    $(...).removeClassWild('class-*');
    
    0 讨论(0)
  • 2021-01-02 07:38

    Get the classes of the element, process it as a string, and put it back:

    $('element').attr(
      'className',
      $('element').attr('className').replace(/\bclass-\d+\b/g, '')
    );
    

    Edit:

    The attr method has since changed, and it no longer reads properties, so you have to use the attribute name class instead of the property name className:

    $('element').attr(
      'class',
      $('element').attr('class').replace(/\bclass-\d+\b/g, '')
    );
    
    0 讨论(0)
  • 2021-01-02 07:41

    ...or you can use a starts-with selector if you know the possible class names you'd like to remove. The nasty part of the task is the sheer number of classes to look for...

    $(document).ready(function () {
         var classesOfInterest = '';
         for(var i = 1; i<=105; i++)
            classesOfInterest += ' ' + 'class-' + i;
         alert(classesOfInterest);
         $("[class^='class-']").removeClass(classesOfInterest);
      });
    
    0 讨论(0)
提交回复
热议问题