我的页面上有一个 div(设置了 id)和一个“打开”/“关闭”它的按钮。默认情况下,此 div 是隐藏的(display: none
)。
单击按钮后,我打开/关闭 div 并向 url 添加或删除哈希标记:window.location.hash = "#about_us_text";
或 window。 location.hash = "";
在每次加载文档时,我检查是否设置了散列标签,以便在输入带有散列标签的 URL 时立即显示 div:
if(window.location.hash == "#about_us_text") {
$("a[href='#about_us_text']").trigger("click"); //trigger the click event which 'slides down' the div
console.log("hash found");
}
这一切都很好,但有一个小问题我无法解决。如果我打开一个新的选项卡/窗口并输入带或不带 has 的 URL,它会按预期工作。但是如果我打开页面,让它加载然后替换同一个选项卡中的 URL,则不会考虑散列标签。例如:
- 我打开 www.mysite.com/index.html -> 没有散列,div 不显示 => 正确
- 我将同一窗口/标签中的 url 替换为 www.mysite.com/index.html#about_us_text -> 页面没有重新加载(文档就绪没有触发),div 没有显示,尽管事实上它应该。
有什么方法可以解决在同一窗口/标签页中更改 URL 时显示/显示 div 的问题吗?非常感谢!
最佳答案
我发现这很方便。原帖在这里 On - window.location.hash - Change?
$(window).on('hashchange', function() {
//.. work ..
});
关于javascript - URL 更改不会重新加载文档 -> 如何检查哈希值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23729178/