location.hash在Safari 4中似乎完全被破坏:它可以初始设置,但不能在任何事件中设置,据我所知,该事件是否由用户触发行动或计时器。location.hash Safari 4中的奇怪
下面是一个例子(我在这里使用jQuery为了简洁,但我无法想象,这个问题是jQuery的专用):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<!-- Include jQuery -->
</head>
<body>
<div id="test">Click the link below to make this text bold.</div>
<p><a href="#test">Bold it!</a></p>
<p id="hashValue"></p>
<script>
$(document).ready(function() {
location.hash = '#normal'; // this works in all browsers
$('a').click(function() {
$('#test').css({'font-weight': 'bold'});
location.hash = '#bold'; // this fails in Safari 4
return false; // prevents link href from affecting hash
});
setInterval(function() {
if (! location.hash.match('bold$')) {
$('#test').css({'font-weight': 'normal'});
}
$('#hashValue').html(location.hash);
}, 100);
});
</script>
</body>
</html>
在Firefox中,行为是你所期望的:当你加载页面,散列被设置为#normal。当您单击该链接时,文本变为粗体并且散列值设置为#bold
。由于散列已更改,间隔函数不起作用。如果将地址栏中的散列更改为其他内容(即不以bold
结尾),则文本将变为粗体。这让后退按钮可以直观地工作:点击回到散列位置#bold
,文本变为粗体。点击其他任何地方,文字不加粗。
但是在Safari 4中,行为是:当您加载页面时,散列值被设置为#normal。就地址栏而言,它会永远保持这种状态。当你点击链接时,即使地址栏中的散列没有改变,文本也会变成粗体,并保持原样。因此,location.hash在内部发生更改(如hashValue
段落所示)。与地址栏的这种不一致具有可怕的后果:如果您单击后退按钮,则文本不加粗;但如果您在此之后点击前进按钮,则不会被重新粗体显示!这完全违反了JavaScript历史库,例如jQuery history plugin。
是否有修正?任何解决方法?我在Mac上的Safari 4.0.1中对此进行了测试。
适用于我(Safari 4.0.1 Mac)。你想发布一个链接到一个不起作用的版本? – Miles 2009-06-23 00:31:18