【问题标题】:How do you remove a class that matches a pattern from the class attribute, but retain the other classes?如何从类属性中删除与模式匹配的类,但保留其他类?
【发布时间】:2012-02-29 08:45:49
【问题描述】:

我想从所有标签的类属性中删除以“蓝色”结尾的类

示例 html

<p class="text_blue happy">this is blue text</p>
<p class="text_red nothappy">this is red text</p>
<img class="img_blue nothappy" />

这将为我提供所有类以“蓝色”结尾的元素

$('[class$=blue]');

如何从类属性中弹出这些匹配的类名?

【问题讨论】:

    标签: jquery jquery-selectors class-attributes


    【解决方案1】:

    您可以使用这样的正则表达式提取整个类名:

    $('[class$="blue"]').each(function() {
        var clsName = this.className.match(/\w*blue\w*/)[0];
    });
    

    您应该意识到$('[class$="blue"]') 对名为class 的整个属性进行操作。我不对单个类名进行操作。所以,它会匹配:

    class="happy text_blue"
    

    但是,它不会匹配:

    class="text_blue happy"
    

    因为类属性不以"blue" 结尾。如果您希望它获取任何包含 "blue" 的类名,而不管它在类名属性中的位置,您都必须使用:

    $('[class*="blue"]').each(function() {
        var clsName = this.className.match(/\w*blue\w*/)[0];
    });
    

    如果你还想过滤掉不以蓝色结尾的类名,你可以用 JS 来做这样的事情:

    $('[class*="blue"]').each(function() {
        var match = this.className.match(/\w*blue(\b|$)/);
        if (match) {
            var clsName = match[0];
        }
    });
    

    如果你想从对象中删除这些类名,你可以这样做:

    $('[class*="blue"]').each(function() {
        var match = this.className.match(/\w*blue(\b|$)/);
        if (match) {
            $(this).removeClass(match[0]);
        }
    });
    

    也可以这样做,看起来更干净一些,但它并不能完美地清除它正在删除的类名周围的额外空白:

    $('[class*="blue"]').each(function() {
        this.className = this.className.replace(/\w*blue(\b|$)/, "").replace(/\s+/g, ' ');
    });
    

    【讨论】:

      【解决方案2】:

      如果您要经常这样做,您可能需要更改分配课程的方式。您可以像这样制作 HTML:

      <p class="text blue happy">this is blue text</p>
      

      然后不要在 CSS 中使用 .text_blue 选择器,而是使用 .text.blue。然后你可以简单地从类中删除“蓝色”。

      【讨论】:

      • 啊,我已经习惯了不链接类,因为 IE6 不支持,猜猜这不再重要了!不过好点。无论如何,有没有办法做我要求的?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-30
      • 2014-09-17
      • 1970-01-01
      相关资源
      最近更新 更多