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
});
- Wrap everything in the document.ready function. Avoid global variables wherever possible.
- Make use of the fact that jQuery manages
thisfor you.thiswill always be what you expect if you pass callback functions directly instead of calling them yourself.