我使用Ajax和哈希导航。

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

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

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

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

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


当前回答

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

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

在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笔记可能对某些人有用。

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

Internet Explorer 8 Firefox 3.6 Chrome 5 Safari 5 Opera 10.6

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

我看了哈希参数使用

window.addEventListener('hashchange', doSomethingWithChangeFunction);

Then

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

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

另一个伟大的实现是jQuery历史,它将使用本机的onhashchange事件,如果它被浏览器支持,如果它不支持,它将使用适当的iframe或间隔浏览器,以确保所有预期的功能被成功模拟。它还提供了一个很好的接口来绑定某些状态。

另一个值得注意的项目是jQuery Ajaxy,它几乎是jQuery历史的一个扩展,将ajax添加到混合。当你开始使用ajax哈希时,它变得相当复杂!