再次播放后尝试再次播放时,其中一个方块没有颜色



https://jsfiddle.net/h0avkn8p/是我的全部代码

当你玩游戏两次,你会看到正确的方块位置从最后一个游戏保持白色,有人知道问题在哪里吗?我认为它来自我的这部分代码。

function genSquareColors(){
if(arr.length > 0){
arr.splice(0, arr.length);
}
for(let i = 0; i < 5; i++){
arr.push(genWrong()); // generates five incorrect squares
}
arr.push(answer);
scramble(arr);
console.log(arr);
return arr;

}
function setColor(){
for(let i = 0; i < squares.length; i++){
squares[i].style.backgroundColor = arr[i];  
}
} 
function colorSquares(){
for(let i = 0; i < squares.length; i++){
squares[i].addEventListener("click", function(){
var clicked = this.style.backgroundColor;
if(clicked === answer){
alert("You won!");
reset();
this.style.backgroundColor = setColor();
} else {
this.style.backgroundColor = "#FFFFFF";
tries--;
}
});
}
}

我看到这里:

function colorSquares(){
for(let i = 0; i < squares.length; i++){
squares[i].addEventListener("click", function(){

每次游戏运行时,为每个方格附加一个新的事件监听器。因此,从第二个游戏开始,点击将为每个监听器产生两个结果。在第三场比赛中,将会有三个结果,等等。因此,点击会导致一个正方形"获胜",并被涂成白色。

在一个持久变量中保存对每个侦听器的引用,然后对每个侦听器调用removeEventListener——或者使用.onclick,这样只保留最新的赋值。

function colorSquares(){
for(let i = 0; i < squares.length; i++){
squares[i].onclick = function(){
var clicked = this.style.backgroundColor;
if(clicked === answer){
alert("You won!");
reset();
this.style.backgroundColor = setColor();
} else {
this.style.backgroundColor = "#FFFFFF";
tries--;
}
};
}
}

这里的情况是,事件侦听器是在相同的项上反复创建的,并且永远不会被清除。如果你console.log在IE。

for (let i = 0; i < squares.length; i++) {
squares[i].addEventListener("click", function() {
var clicked = this.style.backgroundColor;
console.log("On No!");
if(clicked === answer) {
alert("You won!");
reset();
setColor();
} else {
this.style.backgroundColor = "#FFFFFF";
tries--;
}
});
}
}

你会注意到click事件被调用了很多次。

解决方法是在应用事件后存储事件,如果事件已设置,则重置它。IE .

https://jsfiddle.net/djbkmqe6/

或者只应用一次事件。https://jsfiddle.net/ebv1yLdt/

最新更新