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

Forms with Select2 are duplicated when clicking back button on browser in Rails 5(在Rails 5中的浏览器上单击后退按钮时,会复制带有Select2的表单)

本文介绍了在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
        });
    };

这篇关于在Rails 5中的浏览器上单击后退按钮时,会复制带有Select2的表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

基础教程推荐