在Rails 5中的浏览器上单击后退按钮时,会复制带有Select2的表单

_header.html.erb(用于表单部件)

<%= form_for home_path, class: 'home', role: 'search', method: :get do |f| %>
<div class="form-group" style="display:inline;">
 <div class="input-group input-group-md">
 <%= text_field_tag :q, params[:q], placeholder: ... ,class: 'form-control hideOverflow', type: "search" %>
 <%= select_tag "category", options_from_collection_for_select(...),include_blank: true, class: 'form-control hideOverflow', type: "search" %>
 <%if logged_in? %>
  <%= select_tag "location", options_for_select([...], ...),class: 'form-control hideOverflow', type: "search" %>
 <% else %>
  <%= select_tag "location", options_for_select([...], ...),class: 'form-control hideOverflow', include_blank: true, type: "search" %>
 <% end %>
  <span class="input-group-addon"><%= submit_tag "Search", class: "btn-transparent"%></span>
 </div>
</div>
<% end %>

JS代码

<script>
 $( document ).on('turbolinks:load', function() {
    $('select#category').select2({ 
        width: '60%', 
        dropdownAutoWidth : true, 
        placeholder: "Choose a category",
        maximumSelectionLength: 3
    }); 
    $('select#location').select2({
        width: '40%', 
        dropdownAutoWidth : true, 
        minimumResultsForSearch: Infinity
    });
 });

</script>

故障或渲染问题(单击链接可查看图像)

normal

after I click back button from the browser

有没有人能帮我个忙?另外,我的搜索表单在标题部分文件的导航栏中。

如果我在脚本中去掉了$(...).select,一切都会正常工作...我认为selt.js有问题


解决方案

答案如下: https://stackoverflow.com/a/41915129/5758027

我在自己的代码中使用了此解决方案:

    $(document).on('turbolinks:before-cache', function() {     // this approach corrects the select 2 to be duplicated when clicking the back button.
        $('.select-select2').select2('destroy');
        $('.select-search-select2').select2('destroy');
    } );

和观察者:

    $(document).ready( ready );                  //... once document ready
    $(document).ajaxComplete( ready );           //... once ajax is complete
    $(document).on('turbolinks:load', ready );   //... once a link is clicked

    function ready() {
        $(".select-search-select2").select2({
            theme: "bootstrap",
            language: 'es',
            allowClear: true
        });

        $(".select-select2").select2({
            theme: "bootstrap",
            language: 'es',
            minimumResultsForSearch: Infinity,
            allowClear: true
        });
    };

相关文章