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