【问题标题】:link to remove `#` from url without reloading the page在不重新加载页面的情况下从 url 中删除 `#` 的链接
【发布时间】:2019-05-25 14:23:58
【问题描述】:

我有一个名为pound.html的示例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#,再次没有重新加载。但是如果我点击第三个链接,当它把网址放回pound.html(不是#)时,它会重新加载页面。

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


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

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

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

【问题讨论】:

标签: javascript html url anchor single-page-application


【解决方案1】:

怎么样:

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 中删除最后一个字符(在本例中为 #

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 2013-07-07
    • 1970-01-01
    • 2020-04-20
    • 2020-06-27
    • 1970-01-01
    相关资源
    最近更新 更多