我使用Ajax和哈希导航。

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

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

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

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

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


当前回答

var page_url = 'http://www.yoursite.com/'; // full path leading up to hash;
var current_url_w_hash = page_url + window.location.hash; // now you might have something like: http://www.yoursite.com/#123

function TrackHash() {
    if (document.location != page_url + current_url_w_hash) {
        window.location = document.location;
    }
    return false;
}
var RunTabs = setInterval(TrackHash, 200);

就是这样……现在,无论何时点击后退或前进按钮,页面都会根据新的哈希值重新加载。

其他回答

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

var page_url = 'http://www.yoursite.com/'; // full path leading up to hash;
var current_url_w_hash = page_url + window.location.hash; // now you might have something like: http://www.yoursite.com/#123

function TrackHash() {
    if (document.location != page_url + current_url_w_hash) {
        window.location = document.location;
    }
    return false;
}
var RunTabs = setInterval(TrackHash, 200);

就是这样……现在,无论何时点击后退或前进按钮,页面都会根据新的哈希值重新加载。

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

Internet Explorer 8 Firefox 3.6 Chrome 5 Safari 5 Opera 10.6

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

path.js NPM

path.js GitHub

我在一个react应用程序中使用这个,使URL显示不同的参数,取决于用户所处的视图。

我看了哈希参数使用

window.addEventListener('hashchange', doSomethingWithChangeFunction);

Then

function doSomethingWithChangeFunction () {
    let urlParam = window.location.hash; // Get new hash value
    
    // ... Do something with new hash value
};

工作了一个待遇,工作与前进和后退浏览器按钮,也在浏览器历史记录。