首页 > 解决方案 > 在不重新加载页面的情况下从 url 中删除 `#` 的链接

问题描述

我有这个名为的示例 html 页面pound.html

<body onload="alert('loading')">
  <a href="#something">something after #</a><br />
  <a href="#">nothing after #</a><br />
  <a href="">no # at all</a><br >
</body>

我已经添加了一个警报,以便我可以知道页面何时重新加载。

如果我单击第一个链接,则 url 会pound.html#something按预期更改。如果我单击第二个链接,它会pound.html#再次变为 ,而无需重新加载。但是如果我点击第三个链接,当它把 url 放回pound.html(no #) 时,它会重新加载页面。

我总是看到你#在启动时没有的单页应用程序,但是一旦你去了其他地方,然后返回主页,你就剩下#. 有没有办法让它#从 url 中删除而不重新加载页面(比如当你回到主页时)?


如果您从 开始pound.html,然后单击第一个链接并转到pound.html#something,浏览器后退箭头可以让您返回,pound.html而无需重新加载页面。

正如评论中提到的,这里有很多 javascript 解决方案How to remove the hash from window.location (URL) with JavaScript without page refresh?

但是,有人知道是否有办法删除以使链接做到这一点?

标签: javascripthtmlurlanchorsingle-page-application

解决方案


怎么样:

window.location.hash = '1' // add the `#1` to URL (adds hash if its not already there)
window.location.hash = '' // just leave the `#` symbol in URL
window.history.replaceState(null,document.title,location.href.slice(0, -1))

它会从您的 URL 中删除最后一个字符(在本例中为 a #


推荐阅读