jQuery: how to do an after click event in jquery -
i have tic tac toe game, board <table>
, <td>
s cells. every time click on td, appends x img or o img.
this jquery code - note: check var, if there 5 or more clicks on board, start check if wins game.
var player = 1; var check = 0; $("td").bind("click", function(){ if(player==1){ $('<img src="x.png" alt="x" name="x"/>').appendto(this); player=player+1; check+=1; } else { $('<img src="o.jpg" alt="o" name="o"/>').appendto(this); player=player-1; check+=1; } });
my html table this:
<table> <tr> <td id="one"></td> <td id="two"></td> <td id="three"></td> </tr> <tr> <td id="four"></td> <td id="five"></td> <td id="six"></td> </tr> <tr> <td id="seven"></td> <td id="eight"></td> <td id="nine"></td> </tr> </table>
my problem not know winning condition code(for brevity sake, posted here condition when cell 1 2 3 have x marks, player 1 wins), made mouseup function:
$("td").mouseup(function(){ var 1 = $("#one").children("img").attr("name"); var 2 = $("#two").children("img").attr("name"); var 3 = $("#three").children("img").attr("name"); if(check=>5){ if(one=="x"&&two=="x"&&three=="x"){ alert("player 1 wins"); } } });
initially, put code after check+=1 lines, found out there 1 click delay, same thing happening current code. discovered in both cases when click td 2 things @ once: checks if there winning combination (but bec. image not yet inserted nothing) , inserts img.
what think need after click function every time after image inserted check if there winning combination.
add @ end of click handler
var player = 1; var check = 0; $("td").bind("click", function () { if (player == 1) { $('<img src="x.png" alt="x" name="x"/>').appendto(this); player = player + 1; check += 1; } else { $('<img src="o.jpg" alt="o" name="o"/>').appendto(this); player = player - 1; check += 1; } //just add after here var 1 = $("#one").children("img").attr("name"); var 2 = $("#two").children("img").attr("name"); var 3 = $("#three").children("img").attr("name"); if (check >= 5) { if (one == "x" && 2 == "x" && 3 == "x") { alert("player 1 wins"); } } });
demo: fiddle
the problem is, click event fired after mouseup event triggered in mouseup handler value of check
wrong
demo: fiddle
Comments
Post a Comment