简体   繁体   中英

Rails 4 Bootstrap3 Dropdown works, then doesn't work

I put this dropdown on Page A:

<span class="dropdown">
  <button id="dLabel" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Dropdown trigger
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" aria-labelledby="dLabel">
    <li>This
    <li>That
  </ul>
</span>

... and it works just fine.

When I browse to page B and then browse back to page A, the dropdown is seen on the page, but clicking on the dropdown no longer expands the dropdown window. It's as if some aspect of javascript no longer works.

The console in developer tools shows no error and the rails server log shows no error.

If I then stay on Page A and reload the page, the dropdown works. The issue is consistently reproducible.

I am not even sure where to start looking to fix this sort of problem. If a simple fix is not immediately apparent, how about an approach to narrowing the problem down? Many thanks.

My application.js file contains this:

//= require jquery
//= require jquery-ui/sortable
//= require jquery_ujs
//= require jquery.turbolinks
//= require turbolinks
//= require bootstrap-sprockets
//= require cocoon
//= require steps.js.coffee
//= require protocols.js.coffee
//= require retina-1.1.0.js
//= require ie10-viewport-bug-workaround.js

UPDATE:

The answer from luissimo fixes the above problem. Clicking on the dropdown now always works. However, this has uncovered a new issue. The dropdwon window displays properly. When I browse to Page B and then back to page A, the dropdown is offset as seen here:

在此处输入图片说明

在此处输入图片说明

Is there a more fundamental root cause to this trouble?

UPDATE:

changing:

<span class="dropdown">

to:

<span class="btn dropdown">

... fixed the offset problem.

It looks like the order in which you're requiring JS files is not quite right.

From https://github.com/kossnocorp/jquery.turbolinks#usage ,

You should have the following structure in your application.js

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//
// ... your other scripts here ...
//
//= require turbolinks

But your mainfest doesn't conform to the requirements of the gem jquery-turbolinks . Try changing the order and see if it works.

It's because Turbolinks causes a page:change event to occur each time a link is clicked and because of that it reevaluates the Javascript every time. Thats why it works at first but when you change pages it might disfunction. This is the easiest work around for it.

 <script>
   $('#dLabel').dropdown()
 </script>

You can also add data-turbolinks-eval=false to the application.js <script> tag to interrupt the reevaluation after clicking on links.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM