消失的检查标记之谜

时间:2015-06-26 03:38:31

标签: javascript jquery ruby-on-rails ruby ajax

如果用户点击了一个复选框,则会触发下面的代码,但是复选标记有时会消失,因此在应该选中该复选框时将取消选中该复选框。

$(document).on("page:change", function() {
  $(".habit-check").change(function()
  {
    habit = $(this).parent().siblings(".habit-id").first().attr("id");
    level = $(this).siblings(".level-id").first().attr("id");
    if($(this).is(":checked"))
    {
       $.ajax(
       {
         url: "/habits/" + habit + "/levels/" + level + "/days_missed",
         method: "POST"
       });
    }
    else
    {
       $.ajax(
       {
         url: "/habits/" + habit + "/levels/" + level + "/days_missed/1",
         method: "DELETE"
       });
    }
  });
});

# I ALSO TRIED USING LOCAL STORAGE, BUT IT HAD THE SAME PROBLEM.
# VERSION 2

$(document).on("page:change", function() {
{
  $(".habit-check").change(function()
  {
    habit = $(this).parent().siblings(".habit-id").first().attr("id");
    level = $(this).siblings(".level-id").first().attr("id");
    if ($(this).is(":checked")) {
          $.ajax({
            url: "/habits/" + habit + "/levels/" + level + "/days_missed",
            method: "POST"
          });
          localStorage.setItem("habit_"+habit+"_"+level, true);
        } else {
          $.ajax({
            url: "/habits/" + habit + "/levels/" + level + "/days_missed/1",
            method: "DELETE"
          });
          localStorage.setItem("habit_"+habit+"_"+level, false);
        }
  });
});

显示页面调用AJAX

<div class="strikes">
  <% if @habit.current_level_strike %> 
    <div class="btn" id="red"> <label id="<%= @habit.id %>" class="habit-id">Strikes:</label>
  <% else %> 
    <div class="btn" id="gold"> <label id="<%= @habit.id %>" class="habit-id-two">Strikes:</label>
  <% end %>
    <% @habit.levels.each_with_index do |level, index| %>
      <% if @habit.current_level >= (index + 1) %>
        <p>
          <% if @habit.current_level_strike %> 
            <label id="<%= level.id %>" class="level-id">Level <%= index + 1 %>:</label> 
          <% else %> 
            <label id="<%= level.id %>" class="level-id-two">Level <%= index + 1 %>:</label> 
          <% end %>
          <%= check_box_tag nil, true, level.missed_days > 0, {class: "habit-check"} %>
          <%= check_box_tag nil, true, level.missed_days > 1, {class: "habit-check"} %>
          <%= check_box_tag nil, true, level.missed_days > 2, {class: "habit-check"} %>
       </p>
      <% end %>
    <% end %>
  </div>
</div>

这是AJAX触发的内容, days_missed_controller.rb

class DaysMissedController < ApplicationController
  before_action :logged_in_user, only: [:create, :destroy]

  def create
    habit = Habit.find(params[:habit_id])
    habit.missed_days = habit.missed_days + 1
    @habit.save!
    level = habit.levels.find(params[:level_id])
    level.missed_days = level.missed_days + 1
    if level.missed_days == 3
      level.missed_days = 0
      level.days_lost += habit.calculate_days_lost + 1
    end
    level.save!
    head :ok # this returns an empty response with a 200 success status code
  end

  def destroy
    habit = Habit.find(params[:habit_id])
    habit.missed_days = habit.missed_days - 1
    habit.save!
    level = habit.levels.find(params[:level_id])
    level.missed_days = level.missed_days - 1
    level.save!
    head :ok # this returns an empty response with a 200 success status code
  end
end

这是gist。请不要犹豫,要求提供进一步的代码或澄清:]

当我删除了可能是问题的turbolinks时,我也遇到了这个问题,但事实并非如此。

1 个答案:

答案 0 :(得分:2)

好的,跟踪了这个讨厌的人!

问题在于您生成的HTML。事实证明,有问题的人最终会对......无效网址执行AJAX调用(导致404)!

显示视图中,您有以下代码:

<% if @habit.current_level_strike %> 
  <div class="btn" id="red"> <label id="<%= @habit.id %>" class="habit-id">Strikes:</label>
<% else %> 
  <div class="btn" id="gold"> <label id="<%= @habit.id %>" class="habit-id-two">Strikes:</label>
<% end %>

<!-- [...] -->

<% if @habit.current_level_strike %> 
  <label id="<%= level.id %>" class="level-id">Level <%= index + 1 %>:</label> 
<% else %> 
  <label id="<%= level.id %>" class="level-id-two">Level <%= index + 1 %>:</label> 
<% end %>

为什么会有问题?好吧,在您的JavaScript中,您依赖于.habit-id.level-id的确切类:

habit = $(this).parent().siblings(".habit-id").first().attr("id");
level = $(this).siblings(".level-id").first().attr("id");

根据 show view 中的HTML,有时会生成正确的类,有时会有附加*-twohabit-id-twolevel-id-two附录的类)。

如果您尝试修改类名,那么所有类型都与JavaScript(.siblings(".habit-id").siblings(".level-id")所需的格式相同),问题就会消失。

更好的解决方案(是的,可以稍微简化一下;))

如果我们预生成网址,并将其设置为HTML,如下所示:

<div class="strikes">
  <!-- [...] -->
    <% @habit.levels.each_with_index do |level, index| %>
      <% if @habit.current_level >= (index + 1) %>
        <p data-submit-url="<%= habit_level_days_missed_index_path({ habit_id: @habit.id, level_id: level.id }) %>"
           data-delete-url="<%= habit_level_days_missed_path({ habit_id: @habit.id, level_id: level.id, id: 1 }) %>">
          <!-- [...] -->
        </p>
      <% end %>
    <% end %>
  </div>
</div>

然后,您的JavaScript可以简化为:

$(document).on("page:change", function() {
  $(".habit-check").change(function()
  {
    var submitUrl = $(this).parents("p").data("submit-url");
    var deleteUrl = $(this).parents("p").data("delete-url");

    if($(this).is(":checked"))
    {
       $.ajax(
       {
         url: submitUrl,
         method: "POST"
       });
    }
    else
    {
       $.ajax(
       {
         url: deleteUrl,
         method: "DELETE"
       });
    }
  });
});

请注意,生成 delete-url 时,我使用了id的硬编码值,即1(尝试重现原始行为) ,在:

data-delete-url="<%= habit_level_days_missed_path({ habit_id: @habit.id, level_id: level.id, id: 1 }) %>"

对应于:

url: "/habits/" + habit + "/levels/" + level + "/days_missed/1"
你的代码中的

。您 100%确定这是您想要的吗?

希望有所帮助!如果您有任何问题 - 我非常乐意帮助/解释!

祝你好运!