IE6 / 7后退/前进按钮不更改window.location.hash

发布于 2021-01-31 17:38:44

我有一个使用哈希导航的ajax webapp(JSF 2.0)。

我已在此答案的帮助下使用了事件触发功能,并setInterval()在较旧的浏览器(主要是IE6 + 7)中检查了值的变化。

执行此操作的Javascript代码:

window.onload = window.onhashchange = function() {
    lastHash = window.location.hash; // To save a refresh on browsers that don't need it.
    var fragment = document.getElementById('fragment');
    fragment.value = window.location.hash;
    fragment.onchange();
}

// Old Browsers That don't support onhashchange...
var lastHash = window.location.hash;
function checkFragment() {
    if (window.location.hash != lastHash) {
        lastHash = window.location.hash;
        var fragment = document.getElementById('fragment');
        fragment.value = window.location.hash;
        fragment.onchange();
    }
}

这很好。意思是,当我更改哈希值时,AJAX应用会获取通知并进行更新。IE
6/7是其中一个无效的实例。当我按下“后退/前进”按钮时,我可以看到URL栏已使用正确的哈希值更新,但windows.location.hash似乎没有变化,因此我的SetEvent()功能未检测到变化。

有人找到解决方案了吗?谢谢!

关注者
0
被浏览
166
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。

    考虑使用jQuery Hashchange插件来避免IE6 / 7兼容性问题。您可以在此处找到代码示例。可以根据您的情况进行如下更改。

    <script src="jquery.js"></script>
    <script src="jquery-hashchange.js"></script>
    <script>
        $(function(){
            $(window).hashchange(function(){
                $('#fragment').val(location.hash).change();
            });
    
            $(window).hashchange();
        });
    </script>
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看