当我点击带有remote: true的链接时,它不会初始化插件。

3
在我的application.js文件中,我有 .select2 选择器的初始化设置:
$(document).ready(function() {
  $(".select2").select2({
    theme: "bootstrap",
    width: '100%',
    allowClear: true
   });
});

在我的应用程序的另一个部分,我有一个带有 remote: true 链接,它将呈现一个带有 .select2 的下拉列表的新表单。
<%= link_to 'new form' new_feed_item_path, class: 'new-feed-item', remote: true %>

作为响应,它会加载局部文件:new.js.erb
$('.feed-content').html("<%= j(render 'form', feed_item: @feed_item) %>");

但是如果以这种方式加载,选择器无法工作。为什么? 我需要重新初始化js吗? 我在我的应用程序中没有使用turbolinks

1个回答

0
你应该将初始化select的代码块也放在new.js.erb中,因为当你从服务器接收到javascript响应时,$(document).ready事件不会被触发,只有在重新加载或导航时才会触发。为了避免干扰其他selects,你还应该在重新初始化之前销毁所有的selects,代码应该像这样:
$('.feed-content').html("<%= j(render 'form', feed_item: @feed_item) %>");
$(".select2").select2("destroy");
$(".select2").select2({
  theme: "bootstrap",
  width: '100%',
  allowClear: true
 });

我知道这个方法,但我认为它不是最好的。 - Vadim Bekish
你可以使用 $(document).ajaxComplete 替代 document ready,但你别无选择只能重新初始化它。 - ErvalhouS
我已经理解了这个。这种方式不是很方便,但没有其他办法。 - Vadim Bekish

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接