【问题标题】:ajax closest is not affected in ruby on rails最接近的 ajax 在 ruby​​ on rails 中不受影响
【发布时间】:2014-04-22 20:56:16
【问题描述】:

您好,我是 ruby​​ on rails 的新手。我尝试在我的演示网站上做一些 ajax。执行了删除,但我每次都必须刷新。

查看/共享/_feed_item.html.haml

%li{id: feed_item.id}
= image_tag current_user.image_url(:small_thumb).to_s
%span.user
%span.destination
%b Source:
= feed_item.source
%span.destination
%b Destination:
= feed_item.destination
%span.destination
%b Date:
= feed_item.date
%span.timestamp
%b Time:
= feed_item.time
%span.content
%b Comment:
= feed_item.content
%span.timestamp
- if current_user == feed_item.user
= link_to "Delete", feed_item ,method: :delete, data: { confirm: "You sure?" }, title:  "Delete", remote: true, class: "delete_post"

查看/requests/delete.js.haml

$(document).ready(function(){
  $(function(){
    $('.delete_post').bind('ajax:success',function() {
      $(this).closest('li').fadeOut();
    });
  });
});

controller/requests_controller.rb

def destroy
 @request.destroy
 respond_to do |format|
   format.html { redirect_to root_url, notice: "Post deleted" }
   format.js { render nothing: true}
 end
end

原始 html 链接

link

提前致谢。

【问题讨论】:

  • 您的实际问题是什么?当前代码的期望行为和观察到的行为是什么?
  • 我想在不刷新的情况下淡出帖子(通过 ajax)。所以当前代码显示成功删除但不是通过 ajax 。
  • 如果您显示生成的 HTML(浏览器和 jQuery 看到的内容)而不是 html.haml 源代码,将会有更多人能够帮助您。就像现在一样,任何不知道如何阅读您的 haml 文件的人都很难为您提供帮助,但如果您只是公开实际的 HTML,则不需要这些知识来帮助您调试 jQuery。

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


【解决方案1】:

jquery 不工作的原因。问题是涡轮链接。 $(document).ready(function() 不适用于 turbolinks。更多请看description

【讨论】:

    【解决方案2】:

    ABPrime,

    如果closest 不起作用,您可以尝试如下直接 jquery 吗?

    :plain
      $(document).ready(function(){
        $('.delete_post').parent().parent().fadeOut();
      });
    

    【讨论】:

      【解决方案3】:

      我认为这是因为这个选择器没有找到任何元素:

      $(this).closest('li')
      

      jquery closest 函数向上遍历 DOM,这意味着它将查看父母而不是兄弟姐妹。而是尝试使用这个:

      $(this).prev('li')
      

      您总是可以在该行之前放置一个调试器语句,这样您就可以为 $(this) 使用几个不同的 jquery 函数,看看哪个最有效。

      【讨论】:

      • 你能发布一个haml代码输出的示例吗?由此,想出一个可以工作的选择器应该很简单,但我很确定选择器没有找到任何东西。你试过调试器了吗?
      • 我的错,我的意思是说你能不能把原始的 HTML 输出贴出来,让我看看 DOM 的结构是怎样的
      猜你喜欢
      • 1970-01-01
      • 2014-06-17
      • 1970-01-01
      • 1970-01-01
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多