【问题标题】:Uncaught TypeError when trying to bind ajax events to a link in jQuery尝试将 ajax 事件绑定到 jQuery 中的链接时未捕获的 TypeError
【发布时间】:2012-12-18 16:49:34
【问题描述】:

我正在使用带有 UJS 的 Rails。我想在提交之前绑定一些事件以禁用 ajax 链接,并在出现错误时重新启用它。我写了这个 jQuery 来处理这个过程:

$('.post').on('click', 'a[data-toggle="follow"]', function() {
  var elem, href;
  elem = $(this);
  href = elem.attr('href');
  return elem.bind('ajax:loading', elem.attr('href', '#')).bind('ajax:error', elem.attr('href', href));
});

当我故意在我的控制器中模拟一个异常时,我得到了这个 JS 错误:

Uncaught TypeError: Object [object Object] has no method 'apply'

知道为什么会这样吗? Ajax 本身运行良好。仅当出现服务器错误时才会发生这种情况。

li.subscription
  - if signed_in? && current_user.subscribed?(post)
    = link_to "Unfollow", [post, current_user.subscriptions.find_by_post_id(post)], method: :delete, remote: true, 'data-toggle' => 'follow'
  - else
    = link_to "Follow", post_subscriptions_path(post), method: :post, remote: true, 'data-toggle' => 'follow'

【问题讨论】:

    标签: jquery ruby-on-rails ujs


    【解决方案1】:

    jQuery bind function 将处理函数作为第二个参数。但是在这里,您改为为它提供一个 jQuery 对象(即 elem.attr('href', '#') 返回的值)。

    你需要这样的东西:

    return elem.bind('ajax:loading', function() {
        elem.attr('href', '#');
    }).bind('ajax:error', function() {
        elem.attr('href', href);
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-09
      • 1970-01-01
      • 2016-03-19
      • 1970-01-01
      • 2011-07-28
      相关资源
      最近更新 更多