jQuery .click函数不工作没有字符串 [英] jQuery .click function is not working without a string

查看:115
本文介绍了jQuery .click函数不工作没有字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

链接到第一个问题: Ruby on Rails和Jquery:尝试在提交后切换字符

我昨天问过这个问题,并得到了我相信是一些有用的反馈,但现在我现在失去了什么是错误的。我试图在RoR中建立一个井字游戏,目前我在尝试在页面提交后切换玩家。

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表单:

<%= 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板(仅第一个位置):

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:

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

使用 var currentPlayer 在jQuery代码中,.click变得不可点击。但是用X(或分别为O),点击寄存器并正确提交。但是设置的方式,我的印象是 var currentPlayer 应该作为一个字符串,这应该允许这是可点击。

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: Ruby on Rails: Tic-Tac-Toe Game - jQuery click not registering which player is clicking. What am I missing?

推荐答案

检查您的Javascript错误控制台,这是无效的语法,您需要引用

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");

这篇关于jQuery .click函数不工作没有字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆