jQuery点击没有注册点击的玩家.我错过了什么



上一个问题/答案:jQuery.click函数在没有字符串的情况下无法工作

我正试图通过RoR/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();
  });
});

Ruby:

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>

Ruby 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,它显示为未定义。

它是否与以下语法有关:data-current-player: <%=session[:current_player] %>,它应该是data-current-player='<%=session[:current_player] %>'

相关内容

最新更新