指向含标签页内容的页面直连链接无法打开指定标签怎么解决?
问题原因
你现有的代码仅能在标签切换事件触发时执行内容切换,没有处理页面初始化加载时的URL锚点读取逻辑,同时代码存在语法错误:::nth-child(2)为错误写法,伪类nth-child仅需单冒号:。
修复方案
完整实现代码如下:
// 封装标签切换函数,复用逻辑 function switchTab(targetTabId) { // 先隐藏所有标签内容 jQuery('#deo_tab, #sustainablity_tab, #award_tab').hide(); // 移除所有span的active类 jQuery(".effect-1 span").removeClass("active"); switch(targetTabId) { case 'deo_tab': jQuery(".effect-1 span:first-child").addClass("active"); jQuery('#deo_tab').show(); break; case 'sustainablity_tab': jQuery(".effect-1 span:nth-child(2)").addClass("active"); jQuery('#sustainablity_tab').show(); break; case 'award_tab': jQuery(".effect-1 span:last-child").addClass("active"); jQuery('#award_tab').show(); break; default: // 默认展示第一个标签 jQuery(".effect-1 span:first-child").addClass("active"); jQuery('#deo_tab').show(); } } // 页面加载完成后执行 jQuery(document).ready(function() { // 读取URL锚点,去掉开头的# let hash = window.location.hash.slice(1); switchTab(hash); // 可选:监听锚点变化事件,无需刷新页面即可切换标签 jQuery(window).on('hashchange', function() { let newHash = window.location.hash.slice(1); switchTab(newHash); }); // 原有标签点击切换逻辑也可以直接复用switchTab函数 jQuery(".effect-1 span").on('click', function() { let index = jQuery(this).index(); let tabIdArr = ['deo_tab', 'sustainablity_tab', 'award_tab']; switchTab(tabIdArr[index]); // 可选:点击标签时同步更新URL锚点 window.location.hash = tabIdArr[index]; }) })
效果验证
修改完成后访问domainname.com/aboutus#award_tab,页面加载后会自动激活对应第三个标签,展示#award_tab的内容。
内容的提问来源于stack exchange,提问作者Mr Beh
相关产品推荐
相关产品推荐

