【问题标题】:How to force a page to reload if all what was changed in url is hash?如果 url 中的所有更改都是哈希,如何强制页面重新加载?
【发布时间】:2010-12-08 01:39:43
【问题描述】:

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

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

方法一:

window.location.hash = "#" + newhash;

只滚动到这个锚点而不重新加载页面。

方法 #2:

window.location.hash = "#" + newhash;
window.location.reload(true);

有点工作,但它首先滚动到锚点,然后重新加载页面,然后再次滚动到锚点。

方法#3:

window.location.href = window.location.pathname + window.location.search + "&random=" + Math.round(Math.random()*100000) + "#" + newhash;

有效,但我宁愿不向 url 添加随机垃圾。

有没有更好的解决方案?

【问题讨论】:

    标签: javascript url hash location reload


    【解决方案1】:

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

    【讨论】:

    • 起初我不明白你的意思是从 DOM 中删除它。可以,谢谢。
    • 如果您想保持显示更完整,只需删除其nameid 属性就足以满足这些目的 - 节点本身可以​​保留。
    【解决方案2】:

    我有一个在$(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
        }
    });
    

    就我而言,这对 UX 来说很好——可能对其他人不利。

    【讨论】:

    • jQuery 的 ready 事件在window.location = "#myHash" 执行时不会触发,我相信这就是这个问题的重点。但是,此代码对于加载动态内容很有用,例如在重新加载页面时。
    【解决方案3】:

    应该预计#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)
        });
    }
    

    【讨论】:

    • 我从未测试过它,但它应该可以在每个主要浏览器中运行(不包括 IE
    【解决方案4】:

    另一种选择是删除哈希并将其存储在会话存储中以在重新加载时检索:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-01-19
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      • 1970-01-01
      • 2014-08-11
      • 2013-06-20
      相关资源
      最近更新 更多