我正在使用 move 操作在我的 rails 应用程序中进行 AJAX 调用。控制器动作如下:
def move
@game = Game.find_by_id(params[:game])
@player_square = params[:square].to_i
@game.move(@player_square, :player)
@ai_square = GameKeeper.ai_move(@game)
@game.move(@ai_square, :ai) unless @game.squares.compact.count == 9
@winner = GameKeeper.winner(@game) || "" # need to convert nil to an empty string because javascript recognizes null, not nil
end
我的 move.js.erb 包含:
var ai_square = $("#square_<%= @ai_square %>");
ai_square.after("X");
ai_square.remove();
var player_square = $("#square_<%= @player_square %>");
player_square.after("O");
player_square.remove();
if(<%= @winner %>) {
$('#winner').slideToggle("slow");
}
如果我在 javascript 中注释掉 if 块,则其他代码可以正常工作,但如果 if 留在其中,则无论@winner 是否真实,js 都不会执行。可能出了什么问题?
解决方案
因此,无论出于何种原因,如果您使用 erb if 块切换 js if 块,就像这样
<% if @winner %>
$("#winner").slideToggle("slow");
<% end %>
一切正常!很高兴知道为什么原始版本不起作用,但如果其他人有同样的问题,这里有一个解决方案。