[英]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.