我有一个看起来像的div
<div class="draggable resizable abc table shadow"></div>
类(class)没有特定的顺序。如果我执行 $('div').attr('class')
,那么我会得到该 div 的所有类的列表。我想要的是只获取不可resizable
、draggable
或table
的类。在这种情况下,我想要 abc shadow
。我该怎么做。
最佳答案
var all = "draggable resizable abc table shadow";
var some = all.replace(/(?:^|\s)(resizable|draggable|table)(?=\s|$)/g, '');
console.log(some);
// " abc shadow"
console.log(some.replace(/^\s+|\s+$/g,''));
// "abc shadow"
console.log(some.split(/\s+/));
// ["", "abc", "shadow"]
请注意,如果您只需要一个适合设置 className 的字符串,则不需要第二个
到。replace
(您不需要去除前导和尾随空格)
但是,如果您只是想从一个元素中删除一组已知的类,那么简单得多:
$(...).removeClass("draggable resizable table");
替代方案(不需要正则表达式):
var ignore = {resizable:1, draggable:1, table:1};
var all = "draggable resizable abc table shadow".split(' ');
for (var subset=[],i=all.length;i--;) if (!ignore[all[i]]) subset.push(all[i]);
console.log(subset);
// ["shadow","abc"]
console.log(subset.join(' '));
// "shadow abc"
关于javascript - jQuery 获得某些类而不是其他类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7812481/