没有字符串,jQuery .click函数无法正常工作
链接到第一个问题: Ruby on Rails和Jquery:尝试在提交后切换字符
我昨天问了这个问题,并得到了我认为是一些有用的反馈,但现在我现在迷失了什么是错的。 我正在尝试在RoR中构建一个tic-tac-toe游戏,目前我在设置页面后仍然试图切换玩家。
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表单:
<p id="table" data-current-player: >
HTML板(只是第一个位置):
<td data-position="0" class="square ">
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
使用jQuery代码中的var currentPlayer
,.click变得无法点击。 但是使用“X”(或“O”分别),单击注册并正确提交。 但是这个设置的方式,我的印象是var currentPlayer
应该作为一个字符串出来,这应该允许它是可点击的。
链接到下一个问题: jQuery点击没有注册哪个玩家点击。 我错过了什么?
检查你的Javascript错误控制台,这是无效的语法,你需要引用表的id。
var currentPlayer = $('#table').data("current-player");