Twitter Bootstrap - Tabs - URL doesn't change

前端 未结 15 1599
长情又很酷
长情又很酷 2020-11-28 18:53

I\'m using Twitter Bootstrap and its \"tabs\".

I have the following code:

15条回答
  •  醉酒成梦
    2020-11-28 19:03

    For those using Ruby on Rails or any other server side script, you will want to use the anchor option on paths. This is because once the page loads, it does not have the URL hash available. You will want to supply the correct tab via your link or form submission.

    <%= form_for @foo, url: foo_path(@foo, anchor: dom_id(foo)) do |f| %>
    # Or
    <%= link_to 'Foo', foo_path(@foo, anchor: dom_id(foo)) %>
    

    If you are using a prefix to prevent the window from jumping to the id:

    <%= form_for @foo, url: foo_path(@foo, anchor: "bar_#{dom_id(foo)}") do |f| %>
    

    Then you CoffeeScript:

      hash = document.location.hash
      prefix = 'bar_'
      $('.nav-tabs a[href=' + hash.replace(prefix, '') + ']').tab 'show' if hash
      $('.nav-tabs a').on 'shown.bs.tab', (e) ->
        window.location.hash = e.target.hash.replace '#', '#' + prefix
    

    Or JavaScript:

    var hash, prefix;
    
    hash = document.location.hash;
    prefix = 'bar_';
    
    if (hash) {
      $('.nav-tabs a[href=' + hash.replace(prefix, '') + ']').tab('show');
    }
    
    $('.nav-tabs a').on('shown.bs.tab', function(e) {
      window.location.hash = e.target.hash.replace('#', '#' + prefix);
    });
    

    This should work in Bootstrap 3.

提交回复
热议问题