【问题标题】:Jquery - Load tab from different linkJquery - 从不同的链接加载选项卡
【发布时间】:2012-07-30 09:51:52
【问题描述】:

我将以下 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_tab div 并显示活动标签。

【问题讨论】:

    标签: javascript jquery tabs


    【解决方案1】:

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

    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
    });
    

    【讨论】:

    • 没关系,忘记将 id 添加到 extlink。成功了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多