gpt4 book ai didi

javascript - JavaScript 代码中损坏的 "if"语句……

转载 作者:行者123 更新时间:2023-11-30 11:29:17 24 4
gpt4 key购买 nike

我正在尝试运行这段代码,除了 if 语句外,一切似乎都正常。即使存在匹配项,但它仍然不会显示代码中所示的正确答案,而是显示 else 语句中的代码。

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];
var colorDisplay = document.querySelector("#colorDisplay");

colorDisplay.textContent = pickedColor;


for (var i = 0; i < colors.length; i++) {
//add initial colors to squares
squares[i].style.background = colors[i];
//add event listener
squares[i].addEventListener("click", function() {
//get color of picked square
var clickedColor = this.style.background;
//compare to the pickedColor
console.log(clickedColor);
if (clickedColor === pickedColor) {
alert("COORREECCTT");
} else {
alert("WRROONGG!!");
}
});
}
body {
background-color: #232323;
}

.square {
width: 30%;
background-color: purple;
padding-bottom: 30%;
float: left;
margin: 1.66%;
}

#container {
max-width: 600px;
margin: 0 auto;
}

h1 {
color: #fff;
}
<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>
</body>

最佳答案

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];
var colorDisplay = document.querySelector("#colorDisplay");

colorDisplay.textContent = pickedColor;


for (var i = 0; i < colors.length; i++) {
//add initial colors to squares
squares[i].style.background = colors[i];
//add event listener
squares[i].addEventListener("click", function() {
//get color of picked square
var clickedColor = this.style.background;
//compare to the pickedColor
console.log(clickedColor);
if (clickedColor === pickedColor) {
alert("COORREECCTT");
} else {
alert("WRROONGG!!");
}
});
}
body {
background-color: #232323;
}

.square {
width: 30%;
background-color: purple;
padding-bottom: 30%;
float: left;
margin: 1.66%;
}

#container {
max-width: 600px;
margin: 0 auto;
}

h1 {
color: #fff;
}
<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>
</body>

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)"
]

我刚刚添加了空白..

关于javascript - JavaScript 代码中损坏的 "if"语句……,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46842980/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com