Question

I'm trying to practice JS by writing tic-tac-toe. Here's my code so far:

$(document).ready(function() {
    var turn = "X";
    $("td").on("click", function() {
        updateTile();
    });
    function updateTile() {
        if ($(this).html() == "") {
            $(this).html("<h1>" + turn + "</h1>");
            updateTurn();
        }
    }
    function updateTurn() {
        if (turn == "X") {
            turn = "O";
        }
        else if (turn == "O") {
            turn = "X";
        }
    }
});

It's not working. My debugging has led me to believe that the $(this) in updateTile() isn't referring to the $(this) when td is clicked. If so, why is that? $("td") is the object that is calling updateTile(), so shouldn't $(this) refer to the td element?

Was it helpful?

Solution

You are calling an anonymous function instead of your own.

Bind your click like this:

$("td").on("click", updateTile);

EDIT:

The OP want to do other things on click.

So you can use call to be able to use 'this' and an anonym function.

$("td").on("click", function() {
   alert("Click");
   updateTile.call(this);
});

OTHER TIPS

You are out of context, so this is not the this you want.

$(document).ready(function() {
    var turn = "X";
    $("td").on("click", function() {
        updateTile(this);
    });
    function updateTile(that) {
        if ($(that).html() == "") {
            $(that).html("<h1>" + turn + "</h1>");
            updateTurn();
        }
    }
    function updateTurn() {
        if (turn == "X") {
            turn = "O";
        }
        else if (turn == "O") {
            turn = "X";
        }
    }
});

jQuery internally binds the current element to the this context of the function you pass in as the handler. So, just pass in the function directly:

$("td").on("click", updateTile);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top