我有一个简单的 jQuery 选项卡,工作正常。此功能的代码是:
$(document).ready(function() {
var tabHead = $('ul li');
var tabContent = $('.content');
tabContent.not(':first').hide().end();
tabHead.on('click',function() {
tabContent.hide().eq($(this).index()).show();
});
});
标签的 HTML 标记是:
<ul>
<li><a href="#content1">Head 1</a></li>
<li><a href="#content2">Head 2</a></li>
</ul>
<div class="content"> Some Content/........</div>
<div class="content"> Some Content/........</div>
但是,当我单击浏览器的“后退”和“前进”按钮时,只有 url 发生变化,例如
http://some-path/demo-tabs/#tab2
选项卡的内容不显示。如何使选项卡的内容在单击“后退”或“前进”按钮时也显示出来?
最佳答案
监听窗口对象上的 “hashchange”
事件,并在该事件触发时触发对相关 anchor 链接的点击。
您可以使用 jQuery attribute-equals selector 定位正确的链接.看起来像这样:a[href='#tab1']
。您可以通过 window.location.hash
属性从 URL 获取链接的 href。
$(window).on("hashchange", function() {
$("a[href='" + window.location.hash + "']").click();
});
看看这个list of browsers支持 hashchange
事件。
关于javascript - 单击浏览器的后退和前进按钮时在页面选项卡之间导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26824820/