简体   繁体   中英

Maintain Bootstrap's activated nav-tab between page

I am using Bootstrap 3. I currently have 2 pages, one is the view page and one is the edit page. Both pages have a number of nav-tabs, say id= tab1, tab2, tab3.

What I am trying to achieve is, when I'm on tab2 of the view page, if I click the edit button, I will automatically go to tab2 of the edit page. And when I'm on tab3 of the edit page, if I press cancel, I will automatically go to tab3 of the view page.

My current idea is to append tab id to the URL parameter, and on page ready, the page read reads the URL and activated the given tab. This is my code for activating tab.

$(document).ready(function(){
    activaTab(getUrlVars()["tabId"]);
});

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function activaTab(tab){
    $('.nav-tabs a[href="#' + tab + '"]').tab('show');
};

However, I am having troubles appending id to the URL on button click both

<a class="btn">
and
 <button type="submit" class="btn">  

I'm just wondering if anyone have done similar thing? Is there a better solution? With sample code please.

I think you can use:

$('.btn').on('click',function(){
        window.location.href = 'edit.html' + window.location.hash; //the current hash
});

See also:

Below is how I solved this

I gave my ref link a class name called viewToEdit, then I stopped the default behaviour of the link (other wise it will ignore the following code). And I extracted currently activated tab id using jQuery, and append that to my destination URL. Below is my code.

$("a.viewToEdit").on('click', function(event) {
    event.preventDefault();
    var activatedDiv = $('div.tab-pane.form-tab-pane.active');
    if(typeof activatedDiv.attr("id") !== "undefined") {
        $(location).attr('href',$(this).attr("href")+"?tabId="+activatedDiv.attr("id"));
    } else {
        $(location).attr('href',$(this).attr("href"));
    }
});

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