如何更改HTML中的按钮背景颜色?

时间:2019-03-16 21:44:27

标签: javascript html css

我正在尝试使用条件更改按钮的背景色: 如果颜色是“红色”,它将变成“绿色”并反转。 我试图编写这段代码,但没有任何变化。

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>

我在做什么错了?

谢谢。

2 个答案:

答案 0 :(得分:4)

document.getElementsByName的值应在“” -s之间。喜欢

var m = document.getElementsByName("FoodM")[0]

此外,document.getElementsByName返回一个数组,因此,在只有1个具有FoodM名称的元素的情况下,应通过在末尾添加[0]返回该数组的第一个元素。

答案 1 :(得分:-1)

id“食品”在文档中出现多次。 ID应该是唯一的。

相关问题