jQuery .click function is not working without a string

▼魔方 西西 提交于 2019-12-02 17:04:41

问题


Link to first question: Ruby on Rails and Jquery: trying to switch characters after submit

I asked this question yesterday, and got what I believe to be some helpful feedback, but now I am now lost as to what is going wrong. I'm trying to build a tic-tac-toe game in RoR, and at the moment I'm stuck at trying to switch players after the page is submitted.

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)
  switch_player
  redirect_to @game
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 board (just the first position):

<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

With the var currentPlayer in the jQuery code, the .click becomes unclickable. But with "X"(or "O", respectively), the click registers and is submitted correctly. But the way this is set up, I was under the impression that var currentPlayer should be coming out as a string, which should allow this to be clickable.

Link to next question: jQuery click not registering which player is clicking. What am I missing?


回答1:


Check your Javascript error console, that's not valid syntax, you need to quote the id for the table.

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


来源:https://stackoverflow.com/questions/25914641/jquery-click-function-is-not-working-without-a-string

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