【问题标题】:Remove matching class with regex使用正则表达式删除匹配的类
【发布时间】:2013-01-29 09:59:25
【问题描述】:

我想在添加像 type-two 这样的新类之前删除像 type-one 这样的匹配类

HTML:

<div class="demo test">
    <span>One</span>
    <span>Two</span>
    <span>Three</span>
</div>

jQuery :

$(document).on("click" ,".demo > span", function(){
        $(this).addClass("active").siblings().removeClass("active");


        $(this).parents(".demo").removeClass(function(i, c){
            return c.match(/type-[a-z]{0,5}/);
        })

        $(this).parents(".demo").addClass("type-"+$(this).text().toLowerCase());

})

我的代码还在不断添加,无法移除旧的匹配类。

我做错了什么?

演示: http://jsfiddle.net/X5JxV/

【问题讨论】:

    标签: javascript jquery regex match


    【解决方案1】:

    c.match(/type-[a-z]{0,5}/) 正在返回一个包含一个元素的数组。

    您需要指定一个索引,即c.match(/type-[a-z]{0,5}/)[0],但首先您应该检查是否发生了匹配,否则会抛出错误。

    $(this).parents(".demo").removeClass(function(i, c){
        var m = c.match(/type-[a-z]{0,5}/);
        return m ? m[0] : m
    })
    

    【讨论】:

      【解决方案2】:

      这个呢:

      $(document).on("click" ,".demo > span", function(){
          $(this).addClass("active").siblings().removeClass("active");
          $(this).parents(".demo").removeClass().addClass("demo type-" + $(this).text().toLowerCase());
      });
      

      这里我们删除了所有类名称,包括demo,然后用新的type-xxx类重新设置。

      【讨论】:

      • 这也是可行的,但是jQuery在加载之前添加了许多类:D,无论如何谢谢:D
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多