How to open a tab from external link?

后端 未结 2 993
醉酒成梦
醉酒成梦 2020-12-09 20:38

I am using Bootstrap 4 for my web page, I am facing problem with the nav-tabs.

I need to open a Forget Password Tab from the Login Tab Content page

2条回答
  •  自闭症患者
    2020-12-09 21:19

    There are two approaches I can think of to solve this issue:

    1. As Bootstrap 4 does not use the url #hashes for tab navigation, a simple javascript can listen to click events on regular links and trigger additional clicks –under the hood– on the corresponding tabs.
    2. Use url #hashes and open tabs based on the change of that value. This approach also have the advantage that the tabs will be directly linkable, so you could use e.g. example.com#sign-up to open a page with a specific tab opened.

    Below you will find two snippets for each approach.

    1. Under the hood clicks:

    $('.tab-link').on('click', function(event) {
        // Prevent url change
        event.preventDefault();
        
        // `this` is the clicked  tag
        $('[data-toggle="tab"][href="' + this.hash + '"]').trigger('click');
    })
    
    
    
    Forgt password tab
    Sign-up tab

    2. Using hashes in url:

    $(document).ready(function() {
        function onHashChange() {
            var hash = window.location.hash;
    
            if (hash) {
                // using ES6 template string syntax
                $(`[data-toggle="tab"][href="${hash}"]`).trigger('click');
            }
        }
    
        window.addEventListener('hashchange', onHashChange, false);
        onHashChange();
    });
    
    
    
    Forgt password tab
    Sign-up tab

提交回复
热议问题