How do I open a tab from with jQuery UI Tabs from an link outside of the div?

后端 未结 7 1081
清酒与你
清酒与你 2021-01-02 01:09

This may be a little difficult to explain, but I\'ll try my best. I have a product page with two tabs, full description and video. These are done using jQuery UI Tabs.

相关标签:
7条回答
  • 2021-01-02 02:16

    What worked for me was this:

    Html

    <a href="#description" class="open-tab">Open Description Tab</a>
    <a href="#video" class="open-tab">Open Video Tab</a>   
    
    <div id="tabs">
        <ul>
            <li>
                <a href="#description">Full description</a>
            </li>
            <li>
                <a href="#video">Video content</a>
            </li>
        </ul>
    
        <div class="product-collateral">
            <div class="box-collateral box-description">
                <div id="description">
                    Content
                </div>
                <div id="video">
                    <h2 class="video">Video Content</h2>
                </div>
            </div>
        </div>
    </div>
    

    Javascript

    $(document).ready(function () {
        $('#tabs').tabs();
    
        $('.open-tab').click(function (event) {
            var tab = $(this).attr('href');
            $('#tabs').tabs('select', tab);
        });
    });
    

    So what this does is provide a link to both the description and video tabs, which are selected when the link is clicked.

    From here we can see that when selecting a particular tab, we can use either a zero-based index or the href fragment which points to the tab we wish to display.

    This is why the href attributes of the a elements match up with the Ids of the div elements - when one is clicked its href fragment is then used to set the selected tab.


    Update for jQuery UI 1.11

    As jQuery UI has evolved, so to has the API for setting the active tab. As of jQuery UI 1.11, the following code will select the active tab:

    //Selects by the zero-based index
    $('#tabs').tabs("option", "active", index);
    

    Now because we now have to provide a zero-based index, the code I initially provided will no longer work.

    What we need now is an index that can actually be used. One approach is:

    $('.open-tab').click(function (event) {
        var index = $("selector-of-clicked-tab").index();
        $('#tabs').tabs("option", "active", index);
    });
    

    Another is to use HTML5 data- attributes:

    <a href="#description" class="open-tab" data-tab-index="0">Open Description Tab</a>
    <a href="#video" class="open-tab" data-tab-index="1">Open Video Tab</a>
    

    So you can do this when handling the click of these links:

    $('.open-tab').click(function (event) {
        $('#tabs').tabs("option", "active", $(this).data("tab-index"));
    });
    
    0 讨论(0)
提交回复
热议问题