在jQuery选择中使用Reg Ex [英] Using Reg Ex in jQuery selection

查看:108
本文介绍了在jQuery选择中使用Reg Ex的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种使用jQuery从对象中删除与特定格式匹配的所有类的便捷方法.这似乎很适合Reg Ex,但是我似乎在jQuery上找不到任何在选择器中支持它们的文档.我认为StackOverflow将提供更快的解决方案.

I'm looking for a convenient way to use jQuery to remove all classes from an object that match a particular format. This seems like a natural fit for Reg Ex, but I can't seem to find any documentation on jQuery supporting them in selectors. I figured StackOverflow would provide a quicker solution.

鉴于下面的HTML,删除任何以"child_"开头的类的最便捷方法是什么?

Given the HTML below, what is the most convenient means of removing any class that begins with "child_"?

我不需要涉及Reg Ex的解决方案,考虑到问题,这似乎很自然.任何干净的jQuery解决方案都可以使用.

I don't need the solution to involve Reg Ex, it's just what seems natural given the problem. Any clean jQuery solution will work.

<ul id="list">
  <li class="child_1 child_12">Item 1</li>
  <li class="child_4 child_6">Item 2</li>
  <li class="child_3 child_1 stays_put">Item 3</li>
</ul>

我应该澄清一下,目的是删除 class ,而不是元素.完成代码后,所有列表元素仍应存在,但要删除 classes .完成后,它应该看起来像这样.

I should clarify that the purpose is to remove the class, not the element. When the code is done, all the list elements should still be there, but with the classes removed. When completed, it should look like this.

<ul id="list">
  <li class="">Item 1</li>
  <li class=">Item 2</li>
  <li class="stays_put">Item 3</li>
</ul>

推荐答案

我相信这就是您想要的.它会在类名称中找到每个带有child_的元素,然后仅删除带有child_

I believe this is what you want. It finds every element with the child_ in the class name, and then removes only those classes with child_

实时演示

var partial = /^child_/g;
$('[class*=child_]').each(function(){
    var classes = $(this).attr('class').split(' ');

    for(var i=0; i< classes.length;i++){
        if(classes[i].match(partial)){ 
            $(this).removeClass(classes[i]);
        }
    }
});

这篇关于在jQuery选择中使用Reg Ex的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆