Jquery-从不同链接加载选项卡

Jquery - Load tab from different link

本文关键字:加载 选项 链接 Jquery-      更新时间:2023-09-26

我使用下面的jquery代码来创建一个简单的选项卡视图,如果您单击某个选项卡,它将显示该选项卡特定的div。这只适用于单击ul.tabs属性内的选项卡。我如何调整代码以允许在ul.tabs列表之外的同一页面上有一个链接来显示我想要的任何div?

    $(document).ready(function(){
    $('ul.tabs').each(function(){
        // For each set of tabs, we want to keep track of
        // which tab is active and it's associated content
        var $active, $content, $links = $(this).find('a');
        // Use the first link as the initial active tab
        $active = $links.first().addClass('active');
        $content = $($active.attr('href'));
        // Hide the remaining content
        $links.not(':first').each(function () {
            $($(this).attr('href')).hide();
        });
        // Bind the click event handler
        $(this).on('click', 'a', function(e){
            // Make the old tab inactive.
            $active.removeClass('active');
            $content.hide();
            // Update the variables with the new link and content
            $active = $(this);
            $content = $($(this).attr('href'));
            // Make the tab active.
            $active.addClass('active');
            $content.show();
            // Prevent the anchor's default click action
            e.preventDefault();
        });
    });
});

这是html:

            <ul class="tabs">
          <li><a href="#photo_tab">Photos</a></li>
        </ul>
        <div id="photo_tab" class="tabcontent">
          <h3>Section 1</h3>
          <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lobortis placerat dolor id aliquet. Sed a orci in justo blandit commodo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae.</p>
        </div>

因此,我想在页面上其他地方的链接上使用href="#photo_tab",该链接将显示photo_tabdiv并显示活动选项卡。

您可以在正确的选项卡上手动触发点击。

HTML:

<div class="extlink" data-tabid="photo_tab">click me!</div>

<ul class="tabs">
   <li><a href="#photo_tab" id="photo_tab">Photos</a></li>
</ul>

JS:

$('.extlink').click(function(){
    var tabid = $(this).attr('data-tabid');    // this gets the id of the element you want to trigger
    $('#'+tabid).click();   /// this acts as if you clicked on that tab element
});