문제

The setup of my html is I have alphabet imgs inside td. User should click the imgs alphabetically, every correct click the img is removed. If wrong, an xmark will appear.

(not yet in the code: after three wrongs, it's game over, and then i will ask user if he wants to play again or go back to home)

This is my jquery code:

  var error = 0;
        var check = 0;
        $("table img").bind('click',function(){    
            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');


            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>');
                if(error==3){
                    alert("Game Over. Homer will now eat you!");
                    $("table img").unbind("click");
                    $("table img").css("opacity", "0.4");
                }
            }
        }); 

my table in html: just posted the first 6 letters for 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>
도움이 되었습니까?

해결책

Use .appendTo() instead of .add()

Try this:

var error = 0;
        var check = 0;
        $("table img").bind('click',function(){    
            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');
            if(clickedValue ==letterArray[check]){
                $(this).parent().empty(); 
                check+=1;
            } else {
                error+=1;
                $('<td><img src="images/xmark.png" alt="xmark" name="xmark"/></td>').appendTo("tr#error");
                if(error==3){
                    alert("Game Over. Homer will now eat you!");
                    $("table img").unbind("click");
                    $("table img").css("opacity", "0.4");
                }
            }
        }); 

DEMO

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top