【问题标题】:onhashchange with IE 9onhashchange 与 IE 9
【发布时间】:2011-02-13 13:11:55
【问题描述】:
我有以下代码
$(document).ready(function() {
if ("onhashchange" in window) {
alert("The browser supports the hashchange event!");
}
function test(){
alert("hash has changed = " + window.location.hash)
}
window.onhashchange =test;
}
我单击一个更改哈希值的链接,在所有其他浏览器中我收到test 中的警报
但是在 IE 中,我收到第一个警报,说它支持 onhashchange,但是当哈希更改时,什么都没有发生。
有什么想法吗?
【问题讨论】:
标签:
internet-explorer
hashchange
【解决方案1】:
看到这个:link
浏览器是否支持window.onhashchange?
请注意,在 IE7 兼容模式下运行的 IE8 在窗口中报告“onhashchange”为 true,
即使不支持该事件,也要测试document.documentMode。
var docmode = document.documentMode;
if ('onhashchange' in window && (docmode === undefined || docmode > 7 )) {
window.onhashchange = checkHash;
}
【解决方案2】:
在 MSDN 文档page 上有一个示例。
基本上,我删除了他们页面上所有额外的“地图”内容,他们和您的示例之间的唯一区别是它们包含以下元标记:
<meta http-equiv="X-UA-Compatible" content="IE=8" >
我在您的示例中将其添加到 head 标记中,并且效果很好。
这个元标记基本上表示要像在 IE 8 中而不是在 IE 9(仍处于测试阶段)中一样运行页面。
有关此元标记的更多信息,请阅读here
【解决方案3】:
当前所有浏览器都支持 HTML5 中新的 hashchange 事件;无需欺骗您的浏览器认为它是 IE8。
此代码适用于 Win 7 上的 IE 9、FF 5、Safari 5 和 Chrome 12:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script>
window.onhashchange = doThisWhenTheHashChanges;
function changeTheHash()
{
var newHashValue = document.getElementById("newHashInput").value;
var currentLocation = window.location.pathname;
window.location.hash = newHashValue;
}
function doThisWhenTheHashChanges()
{
alert("The hash has changed!");
}
</script>
</head>
<body>
<h1>Hash Change Test</h1>
<form>
<input type="text" id="newHashInput" autofocus>
<input type="button" value="Set" onclick="changeTheHash()">
</form>
</body>
</html>