如果 url 中更改的所有内容都是哈希值,如何强制页面重新加载?
我正在尝试使用不同的 url 哈希重新加载当前页面,但它无法按预期工作。
(澄清我希望它如何工作:重新加载页面,然后滚动到新的哈希值。)
方法#1:
window.location.hash = "#" + newhash;
仅滚动到此锚点而不重新加载页面。
方法#2:
window.location.hash = "#" + newhash;
window.location.reload(true);
有点工作,但它首先滚动到锚点,然后重新加载页面,然后再次滚动到锚点。
方法#3:
window.location.href = window.location.pathname + window.location.search + "&random=" + Math.round(Math.random()*100000) + "#" + newhash;
有效,但我不想向网址中添加随机垃圾。
有更好的解决方案吗?
I am trying to reload current page with different url hash, but it doesn't work as expected.
(Clarification how I want it to work: Reload the page and then scroll to the new hash.)
Approach #1:
window.location.hash = "#" + newhash;
Only scrolls to this anchor without reloading the page.
Approach #2:
window.location.hash = "#" + newhash;
window.location.reload(true);
Kinda works but it first scrolls to the anchor, then reloads the page, then scrolls to the anchor again.
Approach #3:
window.location.href = window.location.pathname + window.location.search + "&random=" + Math.round(Math.random()*100000) + "#" + newhash;
Works but I would rather not add random garbage to the url.
Is there a better solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
删除您要导航到的锚点,然后使用方法#2?由于没有锚点,设置哈希值不应滚动页面。
Remove the anchor you're going to navigate to, then use approach #2? Since there's no anchor, setting the hash shouldn't scroll the page.
我有一个在
$(document).ready()
上触发的 JQuery 函数,它检测在我的情况下是否有附加到 URL 的哈希,所以我保持该函数相同,然后只使用每当检测到哈希更改时强制重新加载:然后我的其他功能 -
就我而言,它对用户体验很好 - 可能对其他人不利。
I had a JQuery function that fired on
$(document).ready()
which detected if there was a hash appended to the URL in my case, so I kept that function the same and then just used a force reload whenever a hash change was detected:Then my other function -
In my case, it was fine for UX -- might not be good for others.
预计 #foo 将滚动到 id 的锚点“foo”。如果您想使用方法 #1 并重新加载它,则此方法可能有效。
It should be expected that #foo will scroll to the anchor of the id, "foo". If you want to use approach #1 and have it reload, this approach might work.
另一种选择是删除哈希值并将其存储在会话存储中,以便在重新加载时检索:
然后在页面顶部可以包含以下代码:
Another option is to remove the hash and store it in session storage to be retrieved on reload:
and then on top of your page you can have the following code: