我有URL: http://example.com#something,我如何删除#一些,而不导致页面刷新?
我尝试了以下解决方案:
window.location.hash = '';
但是,这不会从URL中删除散列符号#。
我有URL: http://example.com#something,我如何删除#一些,而不导致页面刷新?
我尝试了以下解决方案:
window.location.hash = '';
但是,这不会从URL中删除散列符号#。
当前回答
$(window).on('hashchange', function (e) {
history.replaceState('', document.title, e.oldURL);
});
其他回答
const url = new URL(window.location);
url.hash = '';
history.replaceState(null, document.title, url);
$(window).on('hashchange', function (e) {
history.replaceState('', document.title, e.oldURL);
});
这也将删除尾随散列。 例如:http://test.com/123#abc -> http://test.com/123
if(window.history.pushState) {
window.history.pushState('', '/', window.location.pathname)
} else {
window.location.hash = '';
}
function removeLocationHash(){
var noHashURL = window.location.href.replace(/#.*$/, '');
window.history.replaceState('', document.title, noHashURL)
}
window.addEventListener("load", function(){
removeLocationHash();
});
简单优雅:
history.replaceState({}, document.title, "."); // replace / with . to keep url