jQuery-正则表达式选择和removeClass()? [英] jQuery - regexp selecting and removeClass()?

查看:283
本文介绍了jQuery-正则表达式选择和removeClass()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经给我提供了几行几千行的自动生成的HTML文档,我需要清理源代码.通常需要删除类名,例如"table-col-##".这是一个两步问题:

I've been given several auto-generated HTML docs that are thousands of lines long, and I need to clean up the source. Mostly need to remove classnames like "table-col-##". This is a two-step problem:

  1. 选择所有具有table-col-##的类,其中##是0-999之间的整数
  2. 从元素中删除匹配的类,而不删除其他任何类

因此可以归结为:我需要一种方法,如果可能的话,可以在$()选择器中使用正则表达式,然后在each()中获取所选的类-或将regexp应用于$ .removeClass().谁能指出我正确的方向?

So it boils down to: I need a way, if possible, to use regexps in $() selectors, and then either to obtain the selected class in each() - or apply the regexp to $.removeClass(). Can anyone point me in the right direction?

更新:是否有$ .removeClass([selected])功能?这似乎是解决第二部分的最简单方法.

UPDATE: Is there any sort of $.removeClass([selected]) functionality? That seems like the easiest way to solve the second part.

推荐答案

如果只能接受数字,但是也可以有其他字符,我将以类似以下内容开始(未经测试,但在注释的帮助下进行了编辑):

If only numbers are acceptable, but there can be other characters too, I would start with something like this (not tested, but edited with help from comments):

$("[class^='table-col-']").removeClass( function() { /* Matches even table-col-row */
     var toReturn = '',
         classes = this.className.split(' ');
     for(var i = 0; i < classes.length; i++ ) {
         if( /table-col-\d{1,3}/.test( classes[i] ) ) { /* Filters */
             toReturn += classes[i] +' ';
         }
     }
     return toReturn ; /* Returns all classes to be removed */
});

这篇关于jQuery-正则表达式选择和removeClass()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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