简体   繁体   English

根据网址设置活动标签

[英]Setting active tab based on url

I have a simple tabbed interface that switches between hidden div and sets an active state on the appropriate tab when clicked. 我有一个简单的选项卡式界面,可在隐藏的div之间切换,并在单击时在适当的选项卡上设置活动状态。

When someone visits the url of the tab, it shows the contents of that tab only, which is fine. 当某人访问选项卡的url时,它仅显示该选项卡的内容,这很好。

What I need it to do is also set the active state of that tab if you visited that url directly. 如果您直接访问了该URL,我还需要设置该选项卡的活动状态。

I've got url's such as abc.com/index.html#gallery, abc.com/index.html#recipes etc. 我有url,例如abc.com/index.html#gallery、abc.com/index.html#recipes等。

So if you visit abc.com/index.html#recipes - the recipes tab is highlighted. 因此,如果您访问abc.com/index.html#recipes-“食谱”标签将突出显示。

My code is below, thanks in advance for any advice! 我的代码如下,在此先感谢您的任何建议!

    $(function () {
var app = {
        vars: {
            gallery: $('#gallery'),
            tabContent: $('.tabs .tabContent'),
            nav: $('.tabs nav a')
        },
        events: function () {
            //tabs
            app.vars.nav.on('click', function (e) {
                var thisHash = $(this).attr('href');
                app.setHash(thisHash);
                e.preventDefault();
                $('nav a').removeClass('active');
                $(this).addClass('active');
            });

            //hashchange
            $(window).on('hashchange', function() {
                app.checkHash();
            });

        },
        checkHash: function () {
            var hash = app.getHash();

            if (hash == '') {
                app.vars.tabContent.hide();
                app.vars.gallery.show();
            } else {
                app.goTo(hash);
            }

        },
        getHash: function () {
            return window.location.hash;
        },
        setHash: function (id) {
            window.location.hash = id;
        },
        goTo: function (id) {
            app.vars.tabContent.hide();
            $(id).fadeIn();
        }
    }
app.events();
app.checkHash();


});

You need to amend the goTo function to set the active class on the relevant tab. 您需要修改goTo函数以在相关选项卡上设置active类。 Try this: 尝试这个:

goTo: function (id) {
    app.vars.tabContent.hide();
    $(id).fadeIn();
    $('nav a[href="' + id + '"]').addClass('active').siblings().removeClass('active');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM