Javascript 如果url中更改的内容都是哈希,如何强制页面重新加载?

Javascript 如果url中更改的内容都是哈希,如何强制页面重新加载?,javascript,url,hash,location,reload,Javascript,Url,Hash,Location,Reload,我正在尝试用不同的url哈希重新加载当前页面,但它没有按预期工作 (说明我希望它如何工作:重新加载页面,然后滚动到新的哈希。) 方法#1: window.location.hash = "#" + newhash; window.location.hash = "#" + newhash; window.location.reload(true); window.location.href = window.location.pathname + window.location.search

我正在尝试用不同的url哈希重新加载当前页面,但它没有按预期工作

(说明我希望它如何工作:重新加载页面,然后滚动到新的哈希。)

方法#1:

window.location.hash = "#" + newhash;
window.location.hash = "#" + newhash;
window.location.reload(true);
window.location.href = window.location.pathname + window.location.search + "&random=" + Math.round(Math.random()*100000) + "#" + newhash;
仅滚动到此定位点而不重新加载页面

方法#2:

window.location.hash = "#" + newhash;
window.location.hash = "#" + newhash;
window.location.reload(true);
window.location.href = window.location.pathname + window.location.search + "&random=" + Math.round(Math.random()*100000) + "#" + newhash;
有点工作,但它首先滚动到锚点,然后重新加载页面,然后再次滚动到锚点

方法#3:

window.location.hash = "#" + newhash;
window.location.hash = "#" + newhash;
window.location.reload(true);
window.location.href = window.location.pathname + window.location.search + "&random=" + Math.round(Math.random()*100000) + "#" + newhash;
工作,但我宁愿不添加随机垃圾的网址


有更好的解决方案吗?

移除要导航到的锚点,然后使用方法2?由于没有锚定,设置哈希不应该滚动页面。

应该预期#foo将滚动到id“foo”的锚定。如果您想使用方法#1并重新加载它,这种方法可能会奏效

if (Object.defineProperty && Object.getOwnPropertyDescriptor) { // ES5
    var hashDescriptor = Object.getOwnPropertyDescriptor(location, "hash"),
    hashSetter = hashDescriptor.set;
    hashDescriptor.set = function (hash) {
        hashSetter.call(location, hash);
        location.reload(true);
    };
    Object.defineProperty(location, "hash", hashDescriptor);
} else if (location.__lookupSetter__ && location.__defineSetter__) { // JS
    var hashSetter = location.__lookupSetter__("hash");
    location.__defineSetter__("hash", function (hash) {
        hashSetter.call(location, hash);
        location.reload(true)
    });
}

我在
$(document).ready()
上启动了一个JQuery函数,该函数检测到在我的例子中URL是否附加了哈希,因此我保持该函数不变,然后在检测到哈希更改时使用强制重新加载:

$(window).on('hashchange',function(){ 
    window.location.reload(true); 
});
然后我的另一个功能-

$(document).ready(function() {
    var hash = window.location.hash;    
    if(hash) {
           //DO STUFF I WANT TO DO WITH HASHES
    }
});

在我的例子中,这对用户体验很好——可能对其他人不好

另一个选项是删除哈希并将其存储在重新加载时要检索的会话存储中:

var newUrl = location.href + '#myHash';
var splitUrl = newUrl.split('#');
newUrl = splitUrl[0];
if (splitUrl[1]){
    sessionStorage.savedHash = splitUrl[1];
}
location.href = newUrl;
然后在页面顶部,您可以看到以下代码:

var savedHash = sessionStorage.savedHash;
if (savedHash){
    delete sessionStorage.savedHash;
    location.hash = savedHash;
}

起初我不明白你的意思是从DOM中删除它。它可以工作,谢谢。如果您想保持显示更完整,只需删除其
名称
id
属性就足够了-节点本身可以保留。我从未测试过它,但它应该可以在每个主要浏览器中工作(不包括IE jQuery的就绪事件,当
window.location=“#myHash”时不会触发)执行
,我相信这将是这个问题的重点。但是,此代码对于加载动态内容非常有用,例如,如果页面被重新加载。