Javascript 更换一个元件';这是另一节课
难以置信的简单问题,但啤酒和足球的结合让我感到无可救药的不足!(肯定也是复制品,但我找不到它,无论是爱情还是金钱) 我有一个元素Javascript 更换一个元件';这是另一节课,javascript,jquery,regex,Javascript,Jquery,Regex,难以置信的简单问题,但啤酒和足球的结合让我感到无可救药的不足!(肯定也是复制品,但我找不到它,无论是爱情还是金钱) 我有一个元素 <div class="inline-block" id="colour"> 谢谢我为问题的明确性道歉 function setColour(colour) { //check if class exists that has pattern bg-w+ if ($("#colour").attr("class").match(
<div class="inline-block" id="colour">
谢谢我为问题的明确性道歉
function setColour(colour) {
//check if class exists that has pattern bg-w+
if ($("#colour").attr("class").match(/bg-\w+/))
{
var str = $("#colour").attr("class");
var regex = /bg-\w+/;
//get match and remove
$("#colour").removeClass(regex.exec(str)[0]);
}
//always add the new class
$("#colour").addClass('bg-' + colour);
};
鉴于您的问题中的澄清、评论以及您自己发布的答案,您提出的问题似乎是: 如何找到格式为
bg-
的类名,并用新的、给定的颜色名称(如果存在)替换
部分,如果不存在,则添加bg colorname
考虑到这一点——我对用例很好奇,因为它似乎不必要地复杂——我建议采用以下方法:
function setColour(colour) {
$('#colour').attr('class', function (i, oldClasses) {
return 'undefined' === typeof oldClasses ? 'bg-' + colour : oldClasses.replace(/\b(bg-[a-z]+)\b/i, function (a) {
return 'bg-' + colour;
});
});
}
参考资料:
- JavaScript:
- jQuery:
.bg anycolor
不存在,则添加bg color
,如果存在,则将bg anycolor
替换为bg color
?为什么不简单:$('#color').addClass('bg-color').removeClass('bg-anycolor')代码>?我可能误解了您的标准/要求,但据我所知(阅读您的问题),正则表达式是不必要的复杂且完全多余的。这并不十分清楚,但我猜cbg color
实际上类似于bg yellow
,bg red
等。当你使用regex时?嗨,我没有解释好,bg anycolor可以是任何颜色,例如bg red、bg blue等。如果说bg red存在,用bg-yellow替换。那么bg color
会是什么?我…你能把一些演示/信息放在一起,展示可能的场景和应该发生的事情吗?即使是某种类型的ascii表也可能有所帮助,目前我只是感到困惑。我们可以使用带选择器的start$(“div[class^='apple-'],div[class*='apple-'])使用jQuery选择元素,但我认为jQuery.removeClass()参数不能被指定为带选择器的移除类start with bg,其用途是拥有可用颜色设置按钮的列表,单击一个,设置背景颜色并保存到服务器。我使用的是metroui css,而不是函数setColor(color){document.getElementById(“color”).style.backgroundColor=color;} 这意味着要写出所有的十六进制代码,我想换掉这个类会更容易。
//need to add class br-{colour} but also to remove colour if already there
function setColour(colour) {
var ele = $("#colour");
var classname = ele.attr("class") || "";
var classStartIndex = classname.indexOf("bg-");
var classEndIndex = -1;
if (classStartIndex >= 0) {
$.each((classname.substring(classStartIndex, classname.length)).split(""),
function (i, val) {
if (val == " ") {
classEndIndex = i;
return;
}
});
if (classEndIndex == -1)
classEndIndex = classStartIndex.length;
else
classEndIndex = classStartIndex + classEndIndex;
ele.removeClass(classname.substring(classStartIndex, classEndIndex));
}
else {
ele.addClass("bg-" + colour)
}
}
function setColour(colour) {
$('#colour').attr('class', function (i, oldClasses) {
return 'undefined' === typeof oldClasses ? 'bg-' + colour : oldClasses.replace(/\b(bg-[a-z]+)\b/i, function (a) {
return 'bg-' + colour;
});
});
}