jQuery点击没有注册哪个玩家点击。 我错过了什么?
上一个问题/答案: 没有字符串,jQuery .click函数无法正常工作
我正在尝试通过RoR / jQuery / HTML构建一个tic-tac-toe游戏,我无法弄清楚为什么玩家没有在点击上注册。 以前我无法让.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表单:
<p id="table" data-current-player: >
HTML表格(仅限第一个单元格):
<td data-position="0" class="square ">
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
我觉得,鉴于有什么,它应该是有效的。 但是当我运行页面并单击一个单元格时,它提交的内容中没有任何内容。 当它应该是
或o_move时,它出现为
。
我在currentPlayer
上使用了console.log
,它显示为未定义。
它是否与此语法有关: data-current-player: <%=session[:current_player] %>
其中应该是data-current-player='<%=session[:current_player] %>'
?