Javascript 如何切换到带引号的类名
我正在尝试用JavaScript切换一个类。 由此Javascript 如何切换到带引号的类名,javascript,Javascript,我正在尝试用JavaScript切换一个类。 由此 class=product neutral //background color is grey 对此 class=product correct //background color is green if (trueProduct == 12){ document.getElementById("userAnswer").innerHTML = "class='product correct'";
class=product neutral //background color is grey
对此
class=product correct //background color is green
if (trueProduct == 12){
document.getElementById("userAnswer").innerHTML = "class='product correct'";
}
HTML
试试这个
如果要更改所有类名,可以使用此
document.getElementById("userAnswer").className = "product correct";
document.getElementById("userAnswer").className += " correct";
如果您只想在中添加另一个类,可以使用
document.getElementById("userAnswer").className = "product correct";
document.getElementById("userAnswer").className += " correct";
阅读此处的内容您不想更改(在您的情况下,
..>
和
之间的空字符串),但是:
或者,您可以使用:
element.innerHTML
是元素的实际内容,您要查找的是:
if (trueProduct == 12) {
document.getElementById("userAnswer").className = "product correct";
}
使用,这里最方便
var answer = document.getElementById("userAnswer");
answer.classList.remove("neutral");
answer.classList.add("correct");
classList
允许您切换或添加或删除特定类,而无需更改任何其他类。谢谢您,Bergi。这非常有用!+=添加一个(啊…我没想到会这样连接)太酷了!谢谢,BordZoKo连接,你不应该忘记空白。更新了我的答案,请看一看,你只需要一个空格,然后才能找到下一个类名+1,但别忘了提到,它只在最近的浏览器中受支持。“它只在最近的IE中受支持”FTFY:-)不过很好,我不认为IE9不会碰它。对于其他浏览器,我只关心当前的稳定版本,因为它们有自动更新程序(如IE finally,如果它想有用的话)。如何在代码中实现这一点,使用classlist切换类?@user2374200。remove(“neutral”)
从“product neutral”变为“product”,下一次调用。add(“correct”)
使其成为“正确的产品”。没什么复杂的
var answer = document.getElementById("userAnswer");
answer.classList.remove("neutral");
answer.classList.add("correct");