2014-09-18 51 views
1

上一頁提問/回答:jQuery .click function is not working without a stringjQuery點擊沒有註冊哪個玩家點擊。我錯過了什麼?

我試圖通過構建回報率/ jQuery的/ HTML一個井字棋遊戲,我想不通,爲什麼球員都沒有被上點擊註冊。之前我無法得到.val,因爲currentPlayer不是字符串。但現在它只是沒有出現兩種選擇中的任何一種。不知道代碼出錯的地方。

的jQuery:

$(document).ready(function(){ 

    var currentPlayer = $("#table").data("current-player"); 

    $(".square").click(function(){ 
    // Gather the position that was clicked 
    var number = $(this).data("position"); 
    // Locate the game form 
    var form = $("form"); 
    // Locate the input field corresponding to that position 
    var input = $("input[data-position='" + number + "']"); 
    // Set the value of that input field to "X" or "O" 
    input.val(currentPlayer); 
    // Submit the form 
    form.submit(); 
    }); 
}); 

紅寶石:

def update 
    @game = Game.find(params[:id]) 
    @game.update(game_params) 
    redirect_to @game 
    switch_player 
end 

def switch_player 
    session[:current_player] = session[:current_player] == 'X' ? 'O' : 'X' 
end 

HTML形式:

<%= nested_form_for @game do |f| %> 

    <%= f.fields_for :moves do |move_form| %> 
    <p id="table" data-current-player: <%=session[:current_player] %>> 
     <%= move_form.label :position %><br> 
     <%= move_form.text_field :player, data: {position: move_form.object.position} %> 
     <%= move_form.hidden_field :id %> 
    </p> 
    <% end %> 

<input type="Submit"> 
<% end %> 

HTML表(第一小區只):

<div id="board" align = center> 
    <table> 
    <tr> 
     <td data-position="0" class="square <%= class_for_move(0)%>"></td> 

紅寶石class_for_move:

def class_for_move(number) 
    move = @game.moves.find_by(position: number) 
    player = move.player 
    player.downcase + '_move' unless player.blank? 
end 

我覺得,鑑於還有什麼,應該工作。但是當我運行這個頁面並點擊一個單元格時,它就沒有提交任何內容。當它應該是<td data-position="0" class="square x_move"></td>或o_move時,它出現爲<td data-position="0" class="square "></td>

我在currentPlayer上使用了console.log,它顯示爲未定義。

回答

1

難道它與這個語法有關:data-current-player: <%=session[:current_player] %>它應該在哪裏data-current-player='<%=session[:current_player] %>'

+0

只是試過了,它似乎沒有任何區別。我用於currentPlayer的console.log仍然顯示爲未定義。 – Briknthewall 2014-09-18 18:33:21

+0

你最初在哪裏定義'session [:current_player]'?我所看到的是更新後調用switch_player的地方。在開始遊戲時,你有沒有創造初始價值? – cm92 2014-09-18 18:46:56

+0

你其實是對的。我沒有意識到你把'='放在代碼中,而不是':'。這一切都在那之後起作用。所以謝謝。哈哈。 – Briknthewall 2014-09-19 14:46:51