-1
hello. I am taking the first steps in javascript and have a question for which I have not yet found an answer that I really understand.
I’m trying to interact add a click function and a reset function to 3 buttons using the same loop but it only works if I have a loop for each function. I can’t understand why I can’t use the same.
Thank you
ex:
var buttons = document.querySelectorAll("#game button");
var resetbtn =document.getElementById("reset");
var symbol = "X";
for(var i = 0 ; i < 3 ; i++ ) {
buttons[i].onclick = function(){
if(this.textContent == ""){
this.textContent = symbol;
if(symbol=="X"){
symbol= "0";
}
else{
symbol = "X";
}
}
}
function reset(){
//for(var j = 0; j<3; j++){ --> so quando eu altero a variavel abaixo para a do novo loop - J - é que funciona
buttons[i].textContent = "";
}
}
resetbtn.onclick = function(){
reset();
}
}
<div id="game">
<button type="button"></button>
<button type="button"></button>
<button type="button"></button>
</div>
<div>
<button id="reset" type="button">reset</button>
</div>
You are trying to put 3 functions on-click reset button, it will only accept one.
– Daniel Santos