Javascript标签导航问题

时间:2014-05-27 14:43:24

标签: javascript html jquery-tabs

我想知道是否有人可以帮助我修复以下脚本中的错误。

一切正常,直到我用相同的链接添加第二行,然后行为不符合预期。

这是一个隐藏和显示标签的简单脚本。

在某些时候,当点击顶部和底部的链接行时,会同时显示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();
        });
    });
});

1 个答案:

答案 0 :(得分:1)

您在循环的每次迭代中重新声明$active$content个变量。这意味着在一组选项卡中单击Tab3,然后在另一组选项卡中单击Tab2将导致两个选项卡同时出现。

您需要重构代码以将这两个变量移到循环之外,并且可能希望将active变量设置为字符串(例如#tab1),这样它就不会出现这种情况。无论您点击哪个标签集(此时,您的$active变量都指向其中一个标签集中的特定标签)。

以下是我提到的修改的工作示例; http://jsfiddle.net/8cwqH/2/