Best way to make twitter bootstrap tabs persistent

2020-02-07 17:16发布

What is the best way of making these tabs persist?

http://twitter.github.com/bootstrap/javascript.html#tabs

To add some context, this is for a rails application. I'm passing an array [tab1, tab2] to my view, rendering both tabs and using the bootstrap tab plugin to toggle their visibility.

8条回答
ら.Afraid
2楼-- · 2020-02-07 18:18

This code selects the right tab depending on the #hash and adds the right #hash when a tab is clicked. (this uses jquery)

In Coffeescript :

$(document).ready ->
    if location.hash != ''
        $('a[href="'+location.hash+'"]').tab('show')

    $('a[data-toggle="tab"]').on 'shown', (e) ->
        location.hash = $(e.target).attr('href').substr(1)

or in JS :

$(document).ready(function() {
    if (location.hash !== '') $('a[href="' + location.hash + '"]').tab('show');
    return $('a[data-toggle="tab"]').on('shown', function(e) {
      return location.hash = $(e.target).attr('href').substr(1);
    });
});
查看更多
三岁会撩人
3楼-- · 2020-02-07 18:21

Here is another way to solve the Problem.

First add a line to the click event to show the hash in the Addressbar

$('#myTab').on('click', 'a', function (e) {
  e.preventDefault();
  // add this line
  window.location.hash = $(this).attr('href');
  $(this).tab('show');
})

Then make sure that the right tab is activated onload by adding this part to your document ready call.

if(window.location.hash){
   $('#myTab').find('a[href="'+window.location.hash+'"]').tab('show');
}

All together you can write this:

// cache the id
var navbox = $('#myTab');
// activate tab on click
navbox.on('click', 'a', function (e) {
  var $this = $(this);
  // prevent the Default behavior
  e.preventDefault();
  // set the hash to the address bar
  window.location.hash = $this.attr('href');
  // activate the clicked tab
  $this.tab('show');
})

// if we have a hash in the address bar
if(window.location.hash){
  // show right tab on load (read hash from address bar)
  navbox.find('a[href="'+window.location.hash+'"]').tab('show');
}
查看更多
登录 后发表回答