How to get Twitter-Bootstrap navigation to show active link?

前端 未结 22 2119
一整个雨季
一整个雨季 2020-11-27 09:31

I\'m not understanding how Twitter Bootstrap does active links for the navigation. If I have a regular navigation like this (with ruby on rails linking):

<         


        
22条回答
  •  一向
    一向 (楼主)
    2020-11-27 10:25

    Using ruby on Sinatra ..

    I m using bootstrap bare theme, here is the sample navbar code. Note the class name of the element -> .nav - as this is referred in java script.

    / Collect the nav links, forms, and other content for toggling
        #bs-example-navbar-collapse-1.collapse.navbar-collapse
          %ul.nav.navbar-nav
            %li
              %a{:href => "/demo/one"} Page One
            %li
              %a{:href => "/demo/two"} Page Two
            %li
              %a{:href => "/demo/three"} Page Three
    

    in the view page (or partial) add this :javascript, this needs to be executed every time page loads.

    haml view snippet ->

    - content_for :javascript do
      :javascript
          $(function () {
              $.each($('.nav').find('li'), function() {
                  $(this).toggleClass('active',
                      $(this).find('a').attr('href') == window.location.pathname);
              });
          });
    

    In the javascript debugger make sure you have value of 'href' attribute matches with window.location.pathname. This is slightly different than the solution by @Zitrax which helped me fixing my issue.

提交回复
热议问题