繁体   English   中英

如果javascript中的if语句未按预期工作

[英]If statement in javascript not working as intended

该if语句用于将文本更改为一种颜色,每种颜色都有一个按钮。 但是,每个按钮仅将文本更改为红色。 我不确定自己在做什么错。

使用Javascript:

function colorFunction() {

if (document.getElementById("red")) {
document.getElementById('test').style.color = "red";

}else if(document.getElementById("blue")) {
document.getElementById('test').style.color = "blue";

}else if (document.getElementById("black")) {
document.getElementById('test').style.color = "black";

}

}

HTML:

<button id="red" style="background-color:red" type="button" onclick="colorFunction()"><font color="white">Red Text</font></button>


<button id="blue" style="background-color:blue" type="button" onclick="colorFunction()"><font color="white">Blue Text</font></button>

<button id="black" style="background-color:black" type="button" onclick="colorFunction()"><font color="white">Black Text</font></button> 

您需要将单击的按钮引用传递给函数,然后在if...else条件下检查按钮的ID。

<button id="red" style="background-color:red" type="button" onclick="colorFunction(this)"><font color="white">Red Text</font></button>
<button id="blue" style="background-color:blue" type="button" onclick="colorFunction(this)"><font color="white">Blue Text</font></button>
<button id="blue" style="background-color:black" type="button" onclick="colorFunction(this)"><font color="white">Black Text</font></button>

然后

function colorFunction(button) {
    if (button.id == "red") {
        document.getElementById('test').style.color = "red";
    } else if (button.id == "blue") {
        document.getElementById('test').style.color = "blue";
    } else if (button.id == "blue") {
        document.getElementById('test').style.color = "black";
    }
}

演示: 小提琴


如果颜色和按钮ID相同,则

function colorFunction(button) {
    document.getElementById('test').style.color = button.id;
}

演示: 小提琴

这行:

if (document.getElementById("red"))

返回页面中ID为“ red”的ANY元素,由于该元素确实存在,因此计算结果为true。

您可以做的就是对函数和函数调用进行一些更改,并使事情变得简单得多:

<button id="red" style="background-color:red" type="button" onclick="colorFunction('red')"><font color="white">Red Text</font></button>
<button id="blue" style="background-color:blue" type="button" onclick="colorFunction('blue')"><font color="white">Blue Text</font></button>
<button id="black" style="background-color:black" type="button" onclick="colorFunction('black')"><font color="white">Black Text</font>

function colorFunction(colorChoice) {
    document.getElementById('test').style.color = colorChoice;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM