【发布时间】:2014-09-18 13:54:24
【问题描述】:
第一个问题的链接:Ruby on Rails and Jquery: trying to switch characters after submit
我昨天问了这个问题,并得到了一些我认为有用的反馈,但现在我不知道出了什么问题。我正在尝试在 RoR 中构建井字游戏,目前我一直在尝试在页面提交后切换玩家。
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();
});
});
鲁比:
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 表单:
<%= 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>
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 click not registering which player is clicking. What am I missing?
【问题讨论】:
-
您忘记了
id上的引号。$(#table).data("current-player");必须是$("#table").data("current-player");。始终检查您的控制台(在 Chrome 中点击F12)。 -
嗯,解决了这个问题。但是现在单元格/表单显示为空白。并且单元格以
<td data-position="0" class="square "></td>出现,而不是显示<td data-position="0" class="square x_move"></td>或o_move。知道为什么会这样吗? -
我们不知道
class_for_move做了什么,所以,不。 :) -
继续编辑带有 class_for_move 的问题。
-
好像你的
unless player.blank?是真的,所以帮助器的结果是nil,放在类属性中时是一个空白字符串。
标签: jquery html ruby-on-rails ruby click