我使用Ajax和哈希导航。
有没有办法检查window。location。hash是否像这样改变了?
http://example.com/blah#123至http://example.com/blah#456
如果我在文件加载时检查它,它就会工作。
但如果我有#哈希导航,它不工作时,我按浏览器上的后退按钮(所以我从blah#456跳转到blah#123)。
它显示在地址框内,但我无法用JavaScript捕获它。
我使用Ajax和哈希导航。
有没有办法检查window。location。hash是否像这样改变了?
http://example.com/blah#123至http://example.com/blah#456
如果我在文件加载时检查它,它就会工作。
但如果我有#哈希导航,它不工作时,我按浏览器上的后退按钮(所以我从blah#456跳转到blah#123)。
它显示在地址框内,但我无法用JavaScript捕获它。
当前回答
Firefox从3.6开始就有了onhashchange事件。看到window.onhashchange。
其他回答
另一个伟大的实现是jQuery历史,它将使用本机的onhashchange事件,如果它被浏览器支持,如果它不支持,它将使用适当的iframe或间隔浏览器,以确保所有预期的功能被成功模拟。它还提供了一个很好的接口来绑定某些状态。
另一个值得注意的项目是jQuery Ajaxy,它几乎是jQuery历史的一个扩展,将ajax添加到混合。当你开始使用ajax哈希时,它变得相当复杂!
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/
我在一个react应用程序中使用这个,使URL显示不同的参数,取决于用户所处的视图。
我看了哈希参数使用
window.addEventListener('hashchange', doSomethingWithChangeFunction);
Then
function doSomethingWithChangeFunction () {
let urlParam = window.location.hash; // Get new hash value
// ... Do something with new hash value
};
工作了一个待遇,工作与前进和后退浏览器按钮,也在浏览器历史记录。