簡體   English   中英

Javascript標簽導航問題

[英]Javascript tab navigation issue

我想知道是否有人可以幫助我修復以下腳本中的錯誤。

一切正常,直到我添加具有相同鏈接的第二行,然后行為才達到預期。

這是一個隱藏和顯示選項卡的簡單腳本。

有時,單擊鏈接的頂部和底部時,將同時顯示2個選項卡。

上有一個實時示例: http : //jsfiddle.net/8cwqH/1/

<ul class="tabs">
<li><a href="#tab1">Tab1</a></li>
<li><a href="#tab2">Tab2</a></li>
<li><a href="#tab3">Tab3</a></li>
</ul>

<div id="tab1">
 tab1<br />tab1<br />
 tab1<br />tab1<br />
</div>

<div id="tab2">
 tab2<br />tab2<br />
 tab2<br />tab2<br />
</div>

<div id="tab3">
 tab3<br />tab3<br />
 tab3<br />tab3<br />
</div>

<br />

<div class="othertabs">
 <a href="#tab1">Tab1</a>
 <a href="#tab2">Tab2</a>
 <a href="#tab3">Tab3</a>
</div>

<a href="#tab2">tab 2 link</a>

這是腳本:

// Wait until the DOM has loaded before querying the document
$(document).ready(function(){
    $('ul.tabs, div.othertabs').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');

        // If the location.hash matches one of the links, use that as the active tab.
        // If no match is found, use the first link as the initial active tab.
        $active = $($links.filter('[href="'+location.hash+'"]')[0] || $links[0]);
        $active.addClass('active');
        $content = $($active.attr('href'));

        // Hide the remaining content
        $links.not($active).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.fadeIn();

            // Prevent the anchor's default click action
            e.preventDefault();
        });
    });
});

您將在循環的每次迭代中重新聲明$active$content變量。 這意味着在一組選項卡中單擊Tab3,然后在另一組選項卡中單擊Tab2將導致兩個選項卡同時出現。

您需要重構代碼,以將這兩個變量移出循環,並且可能想要將active變量設置為字符串(例如#tab1 ),這樣無論您單擊哪個選項卡集(目前) ,則$active變量將指向其中一個標簽集中的特定標簽)。

這是一個經過修改的有效示例。 http://jsfiddle.net/8cwqH/2/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM