我想使用HTML,CSS和JavaScript(学习)做一个简单的rgb游戏。我需要帮助搞清楚为什么这个'如果'陈述不会工作
我想要发生的是当您单击一种颜色时,它显示“正确”或“错误”,其中静态值为colors[3]
为正确值。我已经测试过多个东西,我认为它与数字与字符串或相关有关,但我不知道。当你点击一种颜色时,他们都会警告“错误”,而不是点击正确的颜色,在这种情况下,颜色[3](青色),它应该显示“正确”。
谢谢。
var colors = [
"rgb(255,0,0)",
"rgb(255,255,0)",
"rgb(0,255,0)",
"rgb(0,255,255)",
"rgb(0,0,255)",
"rgb(255,0,255)"
]
var squares = document.querySelectorAll(".square");
var pickedColor = colors[3];
console.log(pickedColor);
var colorDisplay = document.querySelector("#colorDisplay");
colorDisplay.textContent = pickedColor;
for (var i = 0; i < squares.length; i++){
squares[i].style.background = colors[i];
squares[i].addEventListener("click", function(){
var clickedColor = this.style.background;
if(clickedColor === pickedColor){
alert("correct");
} else {
alert("wrong");
}
});
}
body {
background-color: #232323;
}
.square {
width: 30%;
background: purple;
padding-bottom: 30%;
float: left;
margin: 1.66%;
}
#container {
margin: 0 auto;
max-width: 600px;
}
h1 {
color: white;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Color Game</title>
<link rel="stylesheet" href="colorGame.css">
</head>
<body>
<h1>The Great <span id="colorDisplay">RGB</span> Color Game</h1>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<script type="text/javascript" src="colorGame.js"></script>
</body>
</html>
欢迎使用堆栈!当你说某些事情没有奏效时,让我们知道实际上什么都不起作用。发生了什么不应该发生的行为?你是否在控制台中发生错误? – azium
我会将它添加到开头。基本上,当你点击一种颜色时,他们都会警告“错误”,而不是点击正确的颜色,在这种情况下,颜色[3](青色),它应该显示“正确”。控制台中没有错误。 – nateph
执行'clickedcolor'和'pickcolor'的控制台输出,看看有什么不同 –