我有URL: http://example.com#something,我如何删除#一些,而不导致页面刷新?

我尝试了以下解决方案:

window.location.hash = '';

但是,这不会从URL中删除散列符号#。


当前回答

下面这个怎么样?

window.location。散列= ' '

请注意,我设置哈希到一个单一的空间,而不是一个空字符串。


将散列设置为无效锚也不会导致刷新。例如,

window.location.hash='invalidtag'

但是,我发现上面的解决方案是误导性的。这似乎表明在给定位置上有一个具有给定名称的锚,尽管没有锚。同时,使用空字符串会导致页面移到顶部,这有时是不可接受的。使用空格还可以确保当URL被复制、收藏和再次访问时,页面通常会位于顶部,空格将被忽略。

这是我在StackOverflow上的第一个答案。希望有人觉得它有用,它符合社区标准。

其他回答

要删除散列,可以尝试使用此函数

function remove_hash_from_url()
{
    var uri = window.location.toString();
    if (uri.indexOf("#") > 0) {
        var clean_uri = uri.substring(0, uri.indexOf("#"));
        window.history.replaceState({}, document.title, clean_uri);
    }
}
$(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);

根据上面给出的答案之一,用这个:

var scrollV, scrollH
var loc = window.location;
scrollV = document.body.scrollTop;
scrollH = document.body.scrollLeft;
if ("pushState" in history) {
    history.pushState("", document.title, loc.pathname + loc.search);

    // Restore the scroll offset
    document.body.scrollTop = scrollV;
    document.body.scrollLeft = scrollH;

} else {
    loc.hash = "";

    // Restore the scroll offset
    document.body.scrollTop = scrollV;
    document.body.scrollLeft = scrollH;
}

试试下面的方法:

window.history.back(1);