jquery, why var won't add up and why I cannot see the added img -
just 2 things: why var check won't add up(it's 0), , fix it? second, why cannot add xmark images, after table.
the setup of html have alphabet imgs inside td. user should click imgs alphabetically, every correct click img removed. if wrong, xmark appear.
(not yet in code: after 3 wrongs, it's game over, , ask user if wants play again or go home)
this jquery code:
$("img").click(function(){ var error = 0; var check = 0; var letterarray = new array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'); var clickedvalue = $(this).attr('name'); alert(check); if(clickedvalue ==letterarray[check]){ $(this).parent().empty(); check+=1; } else { error+=1; $("error").add('<td><img src="images/xmark.png" alt="xmark" name="xmark"/></td>'); } });
my table in html: posted first 6 letters brevity.
<table> <tr class="rows"> <td><img src="images/z.png" alt="z" name="z"/></td> <td><img src="images/r.png" alt="r" name="r"/></td> <td><img src="images/s.png" alt="s" name="s"/></td> <td><img src="images/u.png" alt="u" name="u"/></td> <td><img src="images/b.png" alt="b" name="b"/></td> <td><img src="images/a.png" alt="a" name="a"/></td> </tr> </table> <table><tr id="error"></tr></table>
each time function gets run, new check
, error
variables initialized. in order them keep state, need put them in higher (such global) context.
edit: example:
var error = 0, check = 0, letterarray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; $("img").click(function(){ var clickedvalue = $(this).attr('name'); alert(check); if(clickedvalue ==letterarray[check]){ $(this).parent().empty(); check+=1; } else { error+=1; $("error").add('<td><img src="images/xmark.png" alt="xmark" name="xmark"/></td>'); // $("error") looks wrong selector. you're misusing .add() } });
Comments
Post a Comment