繁体   English   中英

jQuery“加载”微调器停止工作

[英]jQuery “loading” spinner stopped working

我在Rails应用中使用了以下代码一段时间了:

 $(function () {

     // Change the link's icon while the request is performing
     $(document).on('click', 'a[data-remote]', function () {
         var icon = $(this).find('i');
         icon.data('old-class', icon.attr('class'));
         icon.attr('class', 'glyphicon glyphicon-refresh spin');
     });

    // Change the link's icon back after it's finished.
    $(document).on('ajax:complete', function (e) {
        var icon = $(e.target).find('i');
        if (icon.data('old-class')) {
            icon.attr('class', icon.data('old-class'));
            icon.data('old-class', null);
        }
    })

}

该代码将一个glyphicon替换为一个“刷新” glyphicon,并将其旋转直到AJAX请求完成,然后将其替换为原始glyphicon。

我最近注意到该代码已停止工作。 AJAX请求工作正常,但在AJAX调用期间我不再得到旋转刷新字形。 升级到Rails 5.1可能导致了问题。

我的Gemfile中确实有gem'jquery gem 'jquery-rails' ,所以我认为Rails 5.1升级是完全向后兼容的。 可能是其他更改导致此中断。

我更新了第一个函数,如下所示:

$('a[data-remote]').on('click', function () {
    var icon = $(this).find('i');
    icon.data('old-class', icon.attr('class'));
    icon.attr('class', 'glyphicon glyphicon-refresh spin');
});

第一次单击按钮时此方法有效,但是如果再次单击同一按钮,则不会显示旋转器。

是否有解决此问题的方法,最好使用标准DOM API? 我搞砸了:

document.querySelectorAll('[data-remote]').onclick = function () { ... }

但还没有运气

我什至接近可行的答案吗? 这将是使用addEventListener的不错选择吗?

您的ajax请求是否还会刷新具有原始侦听器的元素? 发生的事情听起来像听众已经走了。

  1. 单击$('a[data-remote]') ,然后侦听器告诉微调器旋转。

  2. AJAX调用可能会替换页面上的某些元素,包括原始的$('a[data-remote]')元素。

由于侦听器arent在ajax页面加载/刷新后再次添加,因此第二次单击该按钮将不起作用。

只是一个假设,但您也可以在点击处理程序中放入debugger ,然后打开google chrome扩展程序工具。 每次单击按钮时,查看脚本是否暂停。

使用基本修复程序进行更新:

function toggleIcons() {
  $('.regularIcon').toggle();
  $('.spinningIcon').toggle();
}

function toggleButtons() {
  $('.postButton').toggle();
  $('.deleteButton').toggle();
}

$('.postButton').click(function(e) {
  e.preventDefault();
  toggleIcons();

  // ajax call here
  $.ajax({
    type: "GET",
    url: "/route",
    data: data,
    dataType: "JSON",
  }).success(function(json) {
    toggleIcons();
    toggleButtons();
  })
});

// Listener for deleteButton
$('.deleteButton').click(function(e) {
  e.preventDefault();
  toggleIcons();

  // ajax call here
  $.ajax({
    type: "GET",
    url: "/route",
    data: data,
    dataType: "JSON",
  }).success(function(json) {
    toggleIcons();
    toggleButtons();
  })
});

取决于您确保两个按钮的样式都位于DOM上的同一位置。

@Jeff可能是正确的,您正在替换link元素并失去了监听器。 这不会是使用有问题$(document).on('click', 'a[data-remote]', ...)模式,作为元素触发的事件添加声明事件处理程序 ,文件将被抓(请参阅此问题 )。 问题是似乎阻止链接click事件冒泡到document ,并且无法调用侦听器功能。

绑定到body而不是document似乎可以解决此问题:

$("body").on('click', 'a[data-remote]', function () {
     var icon = $(this).find('i');
     icon.data('old-class', icon.attr('class'));
     icon.attr('class', 'glyphicon glyphicon-refresh spin');
 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM