0

I have been trying to make a simple tic tac toe game using html and java script, but i faced a problem that i couldn't figure out its reason. In the following code I am trying to add an event listener to all the cells of the table to change it's content to X on click but when trying it it keeps changing the content of the last cell wherever I press.

   var x = document.querySelectorAll("td");

    for (var i of x ){
       i.addEventListener('click',function(){
        i.textContent = 'x'
       });
   }

But when I change the function to a separate one using the keyword this it works.

  var x = document.querySelectorAll("td");

   function change(){
       this.textContent = 'x';
    }

   for (var i of x ){
        i.addEventListener('click',change);
    }

Can anyone help me why at the first time it keeps changing the last cell only.

That's the HTML code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" href="style1.css">
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

    </head>
    <body>
        <div class="container">
        <div class="jumbotron">
            Welcome To Tic Tac Toe !
            <br>
            <button class="btn btn-primary" id="btn">Reset</button>
        </div>
        <table align="center">
            <tr>
                <td id="1"></td>
                <td id="2"></td>
                <td id="3"></td>
            </tr>
            <tr>
                <td id="4"></td>
                <td id="5"></td>
                <td id="6"></td>
            </tr>
            <tr>
                <td id="7"></td>
                <td id="8"></td>
                <td id="9"></td>
            </tr>
        </table>
         </div>
         <script src="test.js"></script>

    </body>

</html>

0 Answers0