jQuery click not registering which player is clicking. What am I missing?

扶醉桌前 提交于 2020-01-15 11:27:32

问题


Previous question/answer: jQuery .click function is not working without a string

I am trying to build a tic-tac-toe game through RoR/jQuery/HTML and I can't figure out why the players aren't being registered on the clicks. Previously I was unable to get the .val to work at all because currentPlayer wasn't a string. But now it is, only it is not showing up as either of the two choices. Not sure where the code is wrong.

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 form:

<%= 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 table (first cell only):

<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

I feel like, given what is there, it should be working. But when I run the page, and click on a cell, it submits with nothing inside. It comes out as <td data-position="0" class="square "></td> when it should be <td data-position="0" class="square x_move"></td>, or o_move.

I used console.log on currentPlayer and it is showing up as undefined.


回答1:


Could it have something to do with this syntax: data-current-player: <%=session[:current_player] %> where it should be data-current-player='<%=session[:current_player] %>'?



来源:https://stackoverflow.com/questions/25917620/jquery-click-not-registering-which-player-is-clicking-what-am-i-missing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!