_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,一切正常...我认为select.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
        });
    };

08-03 15:56
查看更多