我有这个for循环,当我执行我的代码时,它只是执行' else'声明,如果声明。
截图:
答案 0 :(得分:0)
实际上问题出在这个代码上:
squares[i].addEventListener("click" , function ...
永远不要在循环中添加addEventListener,因为当你点击时,循环已经到达终点了!
我建议您创建一个函数并将其添加到.squares
元素onclick
并在那里执行逻辑。
答案 1 :(得分:0)
var clickedcolor = this.style.backgroundColor;
答案 2 :(得分:0)
我建议使用DOM dataset来保存所选颜色的索引,而不是颜色本身。
var colors=["rgb(99,49,25)","rgb(115,152,170)","rgb(195,171,20)","rgb(55,49,35)","rgb(177,134,98)","rgb(247,100,160)"]
var squares = document.querySelectorAll(".square");
var colorDisplayed = document.querySelector("#colorDisplayed");
var pickedColor = 0;
colorDisplayed.innerText = colors[pickedColor]
var handler = function(e) {
var clickedColor = Number(e.target.dataset.colorIndex); // explicitly transform dataset colorIndex to Number
if (clickedColor === pickedColor) { // if don't want transforming, use `==' instead of `==='
alert("right");
} else {
alert("wrong");
}
}
for (var i = 0; i < squares.length; i++) {
squares[i].style.background = colors[i];
squares[i].dataset.colorIndex = i;
squares[i].addEventListener("click", handler)
}
.square {width: 100px;height: 100px;border: solid 1px black;float: left;}
<div id="colorDisplayed"></div>
<div><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>
另一种方法是使用闭包将i保存到其中。
var colors=["rgb(99,49,25)","rgb(115,152,170)","rgb(195,171,20)","rgb(55,49,35)","rgb(177,134,98)","rgb(247,100,160)"]
var squares = document.querySelectorAll(".square");
var colorDisplayed = document.querySelector("#colorDisplayed");
var pickedColor = 0;
colorDisplayed.innerText = colors[pickedColor]
for (let i = 0; i < squares.length; i++) { // Notice keyword `let' here
squares[i].style.background = colors[i];
squares[i].dataset.colorIndex = i;
squares[i].addEventListener("click", function() {
if (i === pickedColor) { // since i is "letted", i is different each in each event listener function
alert("right");
} else {
alert("wrong");
}
})
}
.square {width: 100px;height: 100px;border: solid 1px black;float: left;}
<div id="colorDisplayed"></div>
<div><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>