使用switch语句更改div背景颜色

V1x*_*III 2 html javascript dom switch-statement

请原谅超级初学者的烦恼,但我正在尝试使用javascript开关进行div更改颜色.我确定这个问题与对参数如何工作的基本误解有关,但正如我所说,我是一个新手.我没有得到任何错误,它只是没有做任何事情.另外,请先在这里发帖,所以如果我在帖子中做了任何不当的事情,我会道歉.

function colorChanger(color) {
  switch(color) {
		case "red":
			document.getElementById("color_box").style.backgroundColor = "red";
			break;
		case "orange":
			document.getElementById("color_box").style.backgroundColor = "orange";
			break;
		case "yellow":
			document.getElementById("color_box").style.backgroundColor = "yellow";
			break;
		case "green":
			document.getElementById("color_box").style.backgroundColor = "green";
			break;
		case "blue":
			document.getElementById("color_box").style.backgroundColor = "blue";
			break;
		case "indigo":
			document.getElementById("color_box").style.backgroundColor = "indigo";
			break;
		case "violet":
			document.getElementById("color_box").style.backgroundColor = "violet";
			break;		
	}
}
Run Code Online (Sandbox Code Playgroud)
@viewport {
    zoom: 1.0;
    width: device-width;
}

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

#color_box {
	width: 20rem;
	height: 20rem;
	border: solid 1px;
}
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html>
<head>
	<title>Color Buttons</title>
	<link rel="stylesheet" type="text/css" href="./color_buttons.css">
	<script src="color_buttons.js"></script>
</head>
<body>
<div id="color_box">
</div>
<div id="button_box">
	<button type="button" id="red" onclick="colorChanger(red)">Red</button>
	<button type="button" id="orange" onclick="colorChanger(orange)">Orange</button>
	<button type="button" id="yellow" onclick="colorChanger(yellow)">Yellow</button>
	<button type="button" id="green" onclick="colorChanger(green)">Green</button>
	<button type="button" id="blue" onclick="colorChanger(blue)">Blue</button>
	<button type="button" id="indigo" onclick="colorChanger(indigo)">Indigo</button>
	<button type="button" id="violet" onclick="colorChanger(violet)">Violet</button>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Bar*_*mar 10

您需要围绕参数引用以使它们成为字符串.

<button type="button" id="red" onclick="colorChanger('red')">Red</button>
Run Code Online (Sandbox Code Playgroud)

没有引号,它正在寻找一个名为的变量red.

您没有收到错误的原因是因为颜色与按钮的ID相同,并且ID都成为引用相应DOM元素的全局变量.所以它的表现就像你写的:

onclick="colorChanger(document.getElementById('red'))"
Run Code Online (Sandbox Code Playgroud)

由于这不等于switch声明中的任何情况,因此没有任何反应.

顺便说一下,为什么还要用switch语句呢?做就是了:

document.getElementById("color_box").style.backgroundColor = color;
Run Code Online (Sandbox Code Playgroud)