How to pass $(this) properly in click jQuery function

You code does not follow the right principles.

$(function(){
    var TURN_X = "X",
        TURN_O = "O", 
        turn   = TURN_O,
        $listCells = $("td");

    function marked() {        // define event handler
        var $this   = $(this),
            tileNum = $this.attr("id");

        if ( !($this.hasClass("marked") ) {
            $this.addClass("marked").text(turn);
            turn = (turn == TURN_X) ? TURN_O : TURN_X;
        }
    }

    $listCells.click(marked);  // attach event handler
});
  1. Wrap everything in the document.ready function. Avoid global variables wherever possible.
  2. Make use of the fact that jQuery manages this for you. this will always be what you expect if you pass callback functions directly instead of calling them yourself.

Leave a Comment