我正在尝试从 HTML 标记中匹配和删除多个类:
//Apply style to item
$('.palette-item').each(function () {
var $this = $(this);
$this.on("click", function () {
target = $("#get-clicked-element-unique-selector").text();
//this works: matches removes one class starting with color
//E.g color1
$(target).removeClass (function (index, css) {
return (css.match (/\bcolor\S+/g) || []).join(' ');
});
//But I want to remove not only classes starting with "color" but
//also classes starting with "grey"
//Have tried the following but not working
$(target).removeClass (function (index, css) {
return (css.match (/\bcolor\S+/g) || (/\bgrey\S+/g) || []).join(' ');
});
//Have tried splitting the two like so but the click event and
//addClass statement don't work after that
$(target).removeClass (function (index, css) {
return (css.match (/\bcolor\S+/g) || []).join(' ');
});
$(target).removeClass (function (index, css) {
return (css.match (/\bgrey\S+/g) || []).join(' ');
});
$(target).addClass($(this).data('color'));
});
});
这是被点击的 html 示例:
<div id="color1-wrapper" class="palette-item" data-color="color1"></div>
<div id="color1a-wrapper" class="palette-item" data-color="color1a"></div>
<div class="grey0 palette-item" data-color="grey0"></div>
<div class="grey1 palette-item" data-color="grey1"></div>
这是“#get-clicked-element-unique-selector”引用:
<p id="get-clicked-element-unique-selector"></p>
非常感谢任何帮助。
最佳答案
我认为错误在于匹配
。
css
参数是一个包含所有类“class1 class2 class3”的字符串(如果直接添加到 html 代码中)。
如果您尝试删除以“颜色”开头的类,我的建议是这样做:
return ((" "+css+" ").match(/\bcolor\S*\b/g)||[]).join(' ');
重点是用空格包裹css
字符串,然后匹配“space+classPrefix+anyCharacters+space”。
这是一个fiddle .
关于javascript - 匹配 css 类并使用 jquery 和 regex 删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23604086/