我正在尝试用条件更改按钮的背景颜色:如果颜色为“红色”,它将变为“绿色”并反转。我试着编写这段代码,但没有任何改变。
function changeColor() {
var f = document.getElementById(food).value;
switch (f) {
case "morning":
var m = document.getElementsByName(FoodM);
if (m.style.backgroundColor == "red") {
m.style.backgroundColor = "green";
} else {
m.style.backgroundColor = "red";
}
break;
case "evning":
var e = document.getElementByName(FoodE)
if (e.style.backgroundColor == "red") {
e.style.backgroundColor = "green";
} else {
e.style.backgroundColor = "red";
}
break;
}
}
<td class="auto-style1" style=" width: 88px">
<input id="food" onclick='changeColor()' name="FoodM" type="button" value="morning" style="width: 88px; height: 75px; background-color:red;font-size:medium" /></td>
<td></td>
<td class="auto-style1" style=" width: 88px">
<input id="food" onclick='changeColor()' name="FoodE" type="button" value="evning" style="width: 88px; height: 75px; background-color:green;font-size:medium" /></td>
</tr>
</table>
<br>
我究竟做错了什么?
谢谢。
document.getElementsByName
的值应该在“-s”之间。喜欢
var m = document.getElementsByName("FoodM")[0]
此外,document.getElementsByName
返回一个数组,所以在你只有1个带有FoodM名称的元素时,你应该通过在末尾添加[0]
来返回数组的第一个元素。
id'food'在文档中出现不止一次。 Ids应该是独一无二的。