【问题标题】:Javascript does not work after AjaxJavascript 在 Ajax 之后不起作用
【发布时间】:2016-09-04 03:30:37
【问题描述】:

所以我看到了一些关于这个主题的帖子,但似乎没有一个对我有用(例如:Jquery function doesn't work after Ajax call;JavaScript does not work after you add new elements)所以我会再问一次。

我有一个小的视频库,我用 _clip_display.html.erb 渲染:

<iframe width="560" height="315" src="//www.youtube.com/embed/<%= clip_to_display %>" frameborder="0" allowfullscreen></iframe>
<% unless desc_to_display.blank? %>
    <p><%= link_to "Description", "#", remote: true, id: "desc-link" %></p>
    <span id="clip-desc">
        <%= desc_to_display %>
    </span>
<% end %>

内部

<section class="clip">
     <%= render "clips/clip_display" %>
</section>

我使用“描述”链接来打开和关闭描述。

clips.coffee:

$(document).on "turbolinks:load", ->
  $("#desc-link").on "click", ->
    $("#clip-desc").fadeToggle()

到目前为止,所有这些都可以正常工作,但是如果我使用 Ajax 删除当前视频并将其替换为新视频,则“说明”链接将不再起作用:

$("section.clip").empty();
$("section.clip").append("<%= j render "clips/clip_display" %>");

【问题讨论】:

标签: javascript ruby-on-rails ajax


【解决方案1】:

您向元素(描述链接)添加了单击事件,该事件正在被 Ajax 成功回调所取代。一旦元素被 Ajax 替换,有界事件将不会触发,因为事件不会再次被初始化。因此,始终将事件回调绑定到可以在文档加载时初始化的静态父元素。你可以使用这样的东西。

$(document).on "turbolinks:load", ->
  $("section.clip").on 'click', 'section.clip', ->
    $("#clip-desc").fadeToggle()

【讨论】:

  • 谢谢,帮助很大:)。只需将 $("section.clip").on 'click', 'section.clip', ... 更改为 $("section.clip").on 'click', '#desc-link', ...
猜你喜欢
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
  • 2015-09-21
  • 1970-01-01
  • 1970-01-01
  • 2014-01-17
  • 2011-01-25
  • 1970-01-01
相关资源
最近更新 更多