javascript - 在不重新加载页面的情况下从 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?
但是,有人知道是否有办法删除以使链接做到这一点?
解决方案
怎么样:
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 #
)
推荐阅读
- java - 从 JVM 内部管理 JVM
- java - [已解决]如何使用 Jackson ObjectMapper 反序列化带有类型元数据的 json 列表?
- hl7-fhir - 参考资源中的 FHIR 搜索
- olap - 如何使用 apache druid 或 clickhouse
- c++ - Mac Xcode 上的 OpenGL
- flutter - 警告 在目标 `WelcomeApp: WelcomeApp` 中配置 `gql_build:serializer_builder` 但这不是已知的 Builder
- sql - 自动化数据转换 (SQL),然后将处理后的数据推送到 Tableau
- sql - 使用 staging_table1 和 table2 的数据插入 table1,同时使用 staging_table1 从 table2 获取数据
- swift - SwiftUI | 如何使用共享表复制本地化字符串?
- cron - 气流 schedule_interval 和 start_date 让它总是触发下一个间隔