2016-12-20 6 views
-1

私は少しTic Tac Toeのゲームを作っています。既に値を持っているセルをクリックしようとすると警告したいと思います。ここまで私がこれまで持っていたことがあります。フィールドが別の値のアラートで占められている場合

var turn = "O"; 
 
    //player 1 = turn = O 
 
    //player2 = turn = X 
 
    var cell = $('#cell'); 
 

 
    function go(cellID) { 
 
     //alert(turn); 
 
     var boxId = "#" + cellID; 
 
     if (cell = null) { 
 
     if (turn == 'O') { 
 
      $(boxId).html("O"); 
 
      turn = 'X'; 
 
     } else { 
 
      if (turn == 'X') { 
 
      $(boxId).html("X"); 
 
      turn = 'O'; 
 
      } 
 
     } 
 
     } else { 
 
     alert('Pick another box') 
 
     } 
 

 
     //alert(cellID); 
 
     $('h2:last').html('Turn: ' + turn); 
 
     return turn; 
 
    }
.cell { 
 
    height: 20px; 
 
    width: 10px; 
 
    background-color: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="gameTable"> 
 
    <table style="width: 100%;"> 
 
    <tr> 
 
     <td onclick="go('C0')" id="C0" class="cell"></td> 
 
     <td onclick="go('C1')" id="C1" class="cell"></td> 
 
     <td onclick="go('C2')" id="C2" class="cell"></td> 
 
    </tr> 
 
    <tr> 
 
     <td onclick="go('C3')" id="C3" class="cell"></td> 
 
     <td onclick="go('C4')" id="C4" class="cell"></td> 
 
     <td onclick="go('C5')" id="C5" class="cell"></td> 
 
    </tr> 
 
    <tr> 
 
     <td onclick="go('C6')" id="C6" class="cell"></td> 
 
     <td onclick="go('C7')" id="C7" class="cell"></td> 
 
     <td onclick="go('C8')" id="C8" class="cell"></td> 
 
    </tr> 
 
    </table> 
 
</div>

+1

をチェックし、あなたの問題は何ですか? 'if(cell = null)'も正しく見えません。if(cell == null) 'をしたくないのですか? – bitten

+0

問題はcell = nullかcell === nullですか? – squiroid

+0

まず、 '=='または '==='であり、条件式では '='ではありません。次に、HTMLコードを投稿すると役立ちます。最後に、[jQueryでnullオブジェクトをチェックする方法](http://stackoverflow.com/questions/477667/how-to-check-null-objects-in-jquery)を読んでください。 –

答えて

1

私はあなたの問題を理解すると思います。 9行目のあなたの小切手はあまり正確ではありません。要素の内容を返す.html()を使用すると、要素の値が空であるかどうかを確認できます。要素が空の場合は、空の文字列が返されます。

if (cell = null) {は、if ($(boxId).html() === '') {他の人が述べたように

See the updated fiddle here

-1

、あなたのif (cell = null)が間違っているとif ($(boxId).html() === '')をする必要がありますになるだろう。

さらに、td要素内のonclickイベントを使用しないでください。代わりに、jqueryの.on('click')イベントを使用する必要があります。

このJSFiddle