我使用Ajax和哈希导航。

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

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

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

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

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


当前回答

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

我看了哈希参数使用

window.addEventListener('hashchange', doSomethingWithChangeFunction);

Then

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

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

其他回答

在IE浏览器中处理History和window.location.hash有很多技巧:

As original question said, if you go from page a.html#b to a.html#c, and then hit the back button, the browser doesn't know that page has changed. Let me say it with an example: window.location.href will be 'a.html#c', no matter if you are in a.html#b or a.html#c. Actually, a.html#b and a.html#c are stored in history only if elements '<a name="#b">' and '<a name="#c">' exists previously in the page. However, if you put an iframe inside a page, navigate from a.html#b to a.html#c in that iframe and then hit the back button, iframe.contentWindow.document.location.href changes as expected. If you use 'document.domain=something' in your code, then you can't access to iframe.contentWindow.document.open()' (and many History Managers does that)

我知道这不是一个真正的回答,但IE-History笔记可能对某些人有用。

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

窗口。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> .

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

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

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

我看了哈希参数使用

window.addEventListener('hashchange', doSomethingWithChangeFunction);

Then

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

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

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

path.js NPM

path.js GitHub