我正在尝试做一个事情,当您单击按钮时,文本将变成绿色,如果您再次单击它,文本将变成蓝色。我这样做的策略是测试文本是绿色还是蓝色,但我不知道如何:
var topcon = document.getElementsByClassName("topchoice");
function show() {
if(topcon.style.color = "blue") {
for (count=0; count < topcon.length; count++) {
topcon[count].style.color = "green";
}
}
else if(topcon.style.color = "green") {
for (count=0; count < topcon.length; count++) {
topcon[count].style.color = "blue";
}
}
}
但是,这不起作用。当我调用 show() 函数时,它只会保持相同的颜色。有谁知道为什么这不起作用?
如果您想知道为什么我使用循环,那是因为没有数组就无法 getElementsByClassName
,因为元素与数组一起使用。
最佳答案
代码中有 2 个问题
- 需要使用比较运算符
==
或===
进行比较 topcon
是一个节点列表,因此它没有style
属性。这将导致您的代码抛出类似Uncaught TypeError: Cannot set property 'color' of undefined
的错误
var topcon = document.getElementsByClassName("topchoice");
function show() {
var el;
for (count = 0; count < topcon.length; count++) {
el = topcon[count];
if (el.style.color == "blue") {
el.style.color = "green";
} else if (el.style.color == "green") {
el.style.color = "blue";
}
}
}
<div class="topchoice" style="color: green">1</div>
<div class="topchoice" style="color: green">1</div>
<div class="topchoice" style="color: green">1</div>
<div class="topchoice" style="color: green">1</div>
<button onclick="show()">Show</button>
关于javascript - 使用 "If statement"获取 Javascript 中彩色文本的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40901613/