我使用Ajax和哈希导航。

有没有办法检查window。location。hash是否像这样改变了?

http://example.com/blah#123至http://example.com/blah#456

如果我在文件加载时检查它,它就会工作。

但如果我有#哈希导航,它不工作时,我按浏览器上的后退按钮(所以我从blah#456跳转到blah#123)。

它显示在地址框内,但我无法用JavaScript捕获它。


当前回答

HTML5指定了一个hashchange事件。现在所有现代浏览器都支持此事件。以下浏览器版本增加了支持:

Internet Explorer 8 Firefox 3.6 Chrome 5 Safari 5 Opera 10.6

其他回答

Firefox从3.6开始就有了onhashchange事件。看到window.onhashchange。

HTML5指定了一个hashchange事件。现在所有现代浏览器都支持此事件。以下浏览器版本增加了支持:

Internet Explorer 8 Firefox 3.6 Chrome 5 Safari 5 Opera 10.6

注意,在Internet Explorer 7和Internet Explorer 9的情况下,if语句将返回true(对于“onhashchange”在windows中),但窗口。onhashchange永远不会触发,所以最好存储哈希值,并在每100毫秒后检查它是否为所有版本的Internet Explorer更改。

    if (("onhashchange" in window) && !($.browser.msie)) {
         window.onhashchange = function () {
              alert(window.location.hash);
         }
         // Or $(window).bind( 'hashchange',function(e) {
         //       alert(window.location.hash);
         //   });
    }
    else {
        var prevHash = window.location.hash;
        window.setInterval(function () {
           if (window.location.hash != prevHash) {
              prevHash = window.location.hash;
              alert(window.location.hash);
           }
        }, 100);
    }

编辑- 从jQuery 1.9开始,$.browser。不支持Msie。来源:http://api.jquery.com/jquery.browser/

简单的例子 单击按钮更改散列

窗口。onhashchange = () => console.log('散列更改-> ${window.location.hash} ') <按钮onclick = " window.location.hash = math . random ()“>哈希到数学。随机> < /按钮 <按钮onclick = " window.location。>哈希到ABC</button> . <按钮onclick = " window.location。hash='XYZ'"> hash到XYZ</button> .

我一直在使用path.js作为客户端路由。我发现它非常简洁和轻量级(它也被发布到NPM),并使用了基于哈希的导航。

path.js NPM

path.js GitHub