Javascript 基于url设置活动选项卡
我有一个简单的选项卡式界面,可以在隐藏div之间切换,并在单击时在相应的选项卡上设置活动状态 当有人访问选项卡的url时,它只显示该选项卡的内容,这很好 如果您直接访问该url,我需要它做的是设置该选项卡的活动状态。 我有一些url,比如abc.com/index.html#gallery、abc.com/index.html#recipes等 因此,如果您访问abc.com/index.html#recipes,recipes选项卡将突出显示 我的代码如下,提前感谢您的建议Javascript 基于url设置活动选项卡,javascript,jquery,tabs,Javascript,Jquery,Tabs,我有一个简单的选项卡式界面,可以在隐藏div之间切换,并在单击时在相应的选项卡上设置活动状态 当有人访问选项卡的url时,它只显示该选项卡的内容,这很好 如果您直接访问该url,我需要它做的是设置该选项卡的活动状态。 我有一些url,比如abc.com/index.html#gallery、abc.com/index.html#recipes等 因此,如果您访问abc.com/index.html#recipes,recipes选项卡将突出显示 我的代码如下,提前感谢您的建议 $(fun
$(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();
});
您需要修改
goTo
功能,以在相关选项卡上设置活动
类。试试这个:
goTo: function (id) {
app.vars.tabContent.hide();
$(id).fadeIn();
$('nav a[href="' + id + '"]').addClass('active').siblings().removeClass('active');
}
您当前的代码有什么问题?目前,如果我访问该页面并在末尾显示has,它会显示正确的内容,但会突出显示错误的选项卡。我需要它根据url突出显示选项卡。