2014-09-18 54 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