简体   繁体   中英

my tic-tac-toe game if condition doesn't work

 let cells = document.querySelectorAll(".cell"); let turn = "x"; cells.forEach( box => { box.addEventListener("click", () => box.classList.add("fill-" + turn)); if ( turn === "x" ) turn = "o"; else turn = "x"; }, { once: true} );
 #board{ border: 2px solid red; width: 210px; height: 210px; margin: auto; }.cell{ border: 1px solid red; display: block; background-color: rgb(241, 239, 239); text-decoration: none; width: 68px; height: 68px; float: left; cursor: pointer; font-size: 60px; text-align: center; line-height: 60px; }.cell:hover{ background-color: rgb(207, 207, 207); }.cell.fill-x::after{ content: "x"; color: blue; }.cell.fill-o::after{ content: "0"; color: red; }
 <.Doctype html> <html> <head> <title>Dooz</title> <meta charset="UFT-8"> <link rel="stylesheet" href="dooz.css"> </head> <body> <div id="board"> <a class="cell"></a> <a class="cell"></a> <a class="cell"></a> <a class="cell"></a> <a class="cell"></a> <a class="cell"></a> <a class="cell"></a> <a class="cell"></a> <a class="cell"></a> </div> <script src="dooz.js"></script> </body> </html>

I'm learning javascript and trying to build a tic-tac-toe game. I want to create an if condition to whether choose "x" or "o" after another, but my code doesn't work probably. inside second if statement line: when it's ( turn = "o" ), it only shows "o" when it's (turn === or == "o"), it only shows "x" What's the problem and how can I fix this?

You are using arrow function as second parameter in click event listener. Arrow functions can only run one statement if you don't specify a body using curly brackets.

let cells = document.querySelectorAll(".cell");

let turn = "x";

cells.forEach( box => {
    box.addEventListener("click",
     () => {
       box.classList.add("fill-" + turn));   

       if ( turn === "x" ) turn = "o";
       else turn = "x";
     });
},
 { once: true}
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM