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

时间:2015-04-21 03:06:41

标签: javascript html

此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> 

2 个答案:

答案 0 :(得分:3)

您需要将单击的按钮引用传递给该函数,然后检查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";
    }
}

演示:Fiddle


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

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

演示:Fiddle

答案 1 :(得分:2)

这一行:

if (document.getElementById("red"))

返回页面中具有id“red”的任何元素,并且由于元素确实存在,因此将评估为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;
}