在消失的对号的奥秘 [英] The Mystery of the Disappearing Checkmarks

查看:90
本文介绍了在消失的对号的奥秘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果用户点击一个复选框低于code会火,但对号有时会消失,因此框未选中它应检查的时候。

If a user clicks a checkbox the below code will fire, but the checkmark will sometimes disappear, the box is therefore unchecked when it should be checked.

$(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

This is what the AJAX fires to, 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

这里是 要点。请不要犹豫,要求进一步code或澄清:]

Here's the gist of it. Please don't hesitate to ask for further code or clarification :]

我也遇到了这个问题,当我删除turbolinks想,可能是问题,但它不是。

I also ran into this problem when I removed turbolinks thinking that might be the issue, but it's not.

推荐答案

好吧,跟踪这个讨厌的一跌!

Ok, tracked this nasty one down!

问题奠定了在生成的HTML。事实证明,有问题的那些最终执行AJAX调用...无效的网址(导致 404 的)!

The problem lays in your HTML generated. It turns out, that the problematic ones end up performing AJAX calls to... invalid URLs (causing 404's)!

在您的显示视图,你有code这样的:

In your show view, you have code like:

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

尽管根据HTML从显示视图,有时会产生适当的类,有时也有类以附录* - 两个习惯-ID-两个水平-ID-两个)。

While according to HTML from show view, sometimes the proper classes are generated, and sometimes there are classes with appendix of *-two (habit-id-two and level-id-two).

如果您尝试固定的类名,所以都是预期你的JavaScript( .siblings(习惯-ID)的形式相同的 .siblings(级-ID)),问题消失。

If you try fixing the class names, so all are of the same form expected by your JavaScript (.siblings(".habit-id") and .siblings(".level-id")), the problem disappears.

更好的解决方案(是的,它可以简化了一点;))

Better solution (yes, it is possible to simplify it a bit ;))

如果我们的 pregenerate 的网址,并将它们以HTML像这样:

What if we pregenerate urls, and set them in HTML like so:

<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可以简化为:

Then, your JavaScript can be simplified to:

$(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"
       });
    }
  });
});

请,予以警告,即生成当删除-网址,我用硬codeD ID 的价值,这是 1 (试图重现原来的行为),在:

Please, be warned, that when generating delete-url, I've used hardcoded value of id, which is 1 (trying to reproduce your original behaviour), in:

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"

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

in your code. Are you 100% sure this is what you want?

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

Hope that helps! If you have any questions - I'm more than happy to help/explain!

祝你好运!

这篇关于在消失的对号的奥秘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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