jquery 与相同脚本冲突

2024-02-06

我正在使用 jquery 将内容加载到选项卡中,并在单击时切换选项卡。我的问题是,我在一页中使用了这个“选项卡切换器”两次,并且它导致了冲突。我对jquery不太有经验,所以我的问题可能在于我在头脑中创建了两次函数。这是我的 jquery(您会注意到有重复的脚本,选择器发生了一些变化,因此“选项卡切换器”看起来不同。

<script type="text/javascript">
    $(document).ready(function() {

        //When page loads...
        $(".tab_content").hide(); //Hide all content
        $("ul.tabs li:first").addClass("active").show(); //Activate first tab
        $(".tab_content:first").show(); //Show first tab content

        //On Click Event
        $("ul.tabs li").click(function() {

            $("ul.tabs li").removeClass("active"); //Remove any "active" class
            $(this).addClass("active"); //Add "active" class to selected tab
            $(".tab_content").hide(); //Hide all tab content

            var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
            $(activeTab).fadeIn(); //Fade in the active ID content
            return false;
        });

    });
    </script>

   <script type="text/javascript">
    $(document).ready(function() {

        //When page loads...
        $(".tabs_content").hide(); //Hide all content
        $("ul.tab li:first").addClass("active").show(); //Activate first tab
        $(".tabs_content:first").show(); //Show first tab content

        //On Click Event
        $("ul.tab li").click(function() {

            $("ul.tab li").removeClass("active"); //Remove any "active" class
            $(this).addClass("active"); //Add "active" class to selected tab
            $(".tabs_content").hide(); //Hide all tab content

            var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
            $(activeTab).fadeIn(); //Fade in the active ID content
            return false;
        });

    });
    </script>

我的 css 是正确的,我知道问题出在上面。第二个脚本工作正常,而第一个脚本则不行。

你可以在这里看到这个直播:link http://vitaminjdesign.com/littlewindow/about/您会注意到第二个脚本工作正常(在底部:玛吉和托德。第一个脚本不起作用(在侧边栏中:类别和档案。)

知道如何解决这个问题吗?


我知道那个脚本 - 我实际上为另一个问题重构了它。该代码非常糟糕,因为它包含许多不好的做法。让我们看看这里可以做什么:

$(".tabs_content").not(':first-child').hide();
var tabs = $('.tabs li');

tabs.filter(':first-child').addClass('active');

tabs.click(function() {
    var current = $(this);

    if(!current.hasClass('active')){
        current.addClass('active').siblings().removeClass('active');
        var activeTab = current.find("a").attr("href");
        current.parent().next().children().hide().filter(activeTab).fadeIn();
    }

    return false;
});

那里 - 所有选项卡都有一个脚本。将所有选项卡容器重命名为tabs。这使用了一些相当重的链接,这确实不是很有效,但是考虑到这里的 DOM,没有太多可做的。使用它,您就不需要两个执行基本相同操作的脚本。

在这里查看它的工作情况:http://jsfiddle.net/E3SFt/2/ http://jsfiddle.net/E3SFt/2/。我为此复制了您的 HTML 字符,并对类名进行了细微修改,如上所述。另请注意,其中有一些无效的 HTML -li里面的元素divs 无效。

Edit:愚蠢的错误,this.hasClass应该current.hasClass

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jquery 与相同脚本冲突 的相关文章