jQuery 获取某些类,但不获取其他类
我有一个看起来像
<div class="draggable resizable abc table shadow"></div>
Classes 没有特定顺序的 div。如果我执行 $('div').attr('class')
然后我会得到该 div 的所有类的列表。我想要的是只获取不可调整大小、可拖动或表格的类。在这种情况下,我想要abc Shadow
。我该怎么做。
I have a div that looks like
<div class="draggable resizable abc table shadow"></div>
Clases are in no specific order. If I do $('div').attr('class')
then I get a list of all the classes for that div. What I want is to only get classes that are not resizable
, draggable
or table
. In this case i want abc shadow
. How do I do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
请注意,如果您想要的只是一个适合设置
className
的字符串,则不需要第二个replace
(您不需要去除前导和尾随空格) > 到。但是,如果您尝试从元素中删除一组已知类,那么最好简单地:
替代方案(不需要正则表达式):
Note that you don't need the second
replace
(you don't need to strip off leading and trailing whitespace) if all you want is a string that's appropriate for setting theclassName
to.But then, if you're trying to just remove a set of known classes from an element, far better to simply:
Alternative (without needing a regex):
插件:
用法:
A plugin:
Usage:
@Phrogz 答案很好。显然,他是一个正则表达式奇才。由于我不太了解正则表达式,所以这是我的看法:
这是一个工作小提琴来说明 。
@Phrogz answer is a good one. Apparently, he's a regex wiz. Since I don't know regex that well, here's my take on it:
Here's a working fiddle to illustrate.
您可以使用
.hasClass
检查各个类。You can check for individual classes using
.hasClass
.这是在这里得到的答案。 使用 jQuery 获取元素的类列表。
您可以扩展它以获取数组中不可“调整大小、可拖动或表格”的字符串
This was answered here. Get class list for element with jQuery.
You can extend this to just get the strings in the array that are not "resizable, draggable or table"
看看这个 jsFiddle,我有一些像你想要的东西。
另外,看看 jQuery :not 选择器
have a look at this jsFiddle, I have something working like what you wanted.
Also, have a look at jQuery :not selectors