简体   繁体   中英

Prevent the show event for bootstrap tabs

I'm working with bootstrap nav-tabs , when a tab's show event is triggered, I do an if test if it failed I call the e.preventDefault(); as following :

$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
    if(test){
        e.preventDefault();
        return false;
    }
});

Which works in this case.

In another scenario I call an ajax function and it will return me a result, based on this result I want to prevent the default behavior of the show event, as following :

$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {
    checkPageLayoutsAreSelected();
    window.getLayoutAreSelectedResult = function(xhr, status, args) {
        if(args.returnedValue === false){
            e.preventDefault();
            console.log('Hello.');
            return false;
        }
    };
}); 

The checkPageLayoutsAreSelected() function will execute an ajax call and if it succeed it will call the window.getLayoutAreSelectedResult() function. Please, notice that the Hello logged message is printed in this case.

The problem here is that the tab is always shown even if I called the e.preventDefault(); .

I think that the show event is already triggered before the ajax call finishes.

How can I solve this ?

I think there is another method to complete this, which is to remember the latest selected tab, and then instead of calling the e.preventDefault() we show the latest selected tab before the current selected tab, so following :

$('a[data-toggle="tab"]').on('show.bs.tab', function (e) {

    //TODO : get the latest selected tab before this current selected tab

    checkPageLayoutsAreSelected();
    window.getLayoutAreSelectedResult = function(xhr, status, args) {
        if(args.returnedValue === false){
            var tab = $(".tabs").find("[data-target='"+latestSelectedTab+"']")[0];
            $(tab).tab('show');
        }
    };
});

But I couldn't figure how I can get the latest selected tab before the current selected tab.

In principle I'd suggest to avoid linking page navigation with ajax calls as this will add a "hiccup" in your UI, meaning that the tab will wait until the call is complete and then do whatever you want it to do.

I'd suggest you load the values that determine if the tab content should appear or not on page load and not on tab click. You could store those values either on hidden inputs or on an array and check against that and your browsing experience would be ok.

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