Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
534 views
in Technique[技术] by (71.8m points)

jquery - show tab with external link with onclick in bootstrap 3

I want to link to a bootstrap 3.2.0 tab with a link like this:

<a href="#tab_i_want_to_link" onclick="something()">Tab name</a>

Thanks!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is a comment thread here: https://github.com/twbs/bootstrap/issues/2415 and NONE of the solutions work as smoothly as this.

SOURCE: http://timforsythe.com/blog/hashtabs/

DEMO: https://jsbin.com/quvelo/2/

This solution links to tabs outside, inside, and wherever you want with a regular url.

  $(window).load(function() { 

    // cache the id
    var navbox = $('.nav-tabs');

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

    // will show tab based on hash
    function refreshHash() {
      navbox.find('a[href="'+window.location.hash+'"]').tab('show');
    }

    // show tab if hash changes in address bar
    $(window).bind('hashchange', refreshHash);
    
    // read has from address bar and show it
    if(window.location.hash) {
      // show tab on load
      refreshHash();
    }
    
});

You put this js AFTER your bootstrap.js inside the functions where you call the tooltip or popover (for example). I have a bootstrap-initializations.js file loaded after bootstrap.min.js in my document.

USAGE: The same as you would use to link to an anchor:

<a href="mypage.html#tabID">Link</a>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...