尝试将ajax事件绑定到jQuery中的链接时出现未捕获类型错误

尝试将ajax事件绑定到jQuery中的链接时出现未捕获类型错误,jquery,ruby-on-rails,ujs,Jquery,Ruby On Rails,Ujs,我将Rails与UJS一起使用。我想在提交之前绑定一些事件以禁用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

我将Rails与UJS一起使用。我想在提交之前绑定一些事件以禁用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错误:

未捕获类型错误:对象[Object Object]没有方法“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将处理程序函数作为第二个参数。但是,这里您为它提供了一个jQuery对象(即
elem.attr('href','#')
返回的值)

你需要像这样的东西:

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