2014-05-22 201 views
1

我有以下HTML:錨導航和歷史變化

<a href="./page1.html">page 1</a> 

當點擊鏈接,一個新的歷史條目添加預期。
現在我將其更改爲:

<a href="./page1.html" onclick="func(event)">page 1</a> 
<script type="text/javascript"> 
function func(event) { 
    window.history.replaceState(null, '', "./page1.html"); 
} 
</script> 

現在,當我點擊這個鏈接,歷史不會改變。
我無法理解爲什麼。我沒有阻止主播的動作(由event.preventDefault()或返回false),所以我期望從主播添加新的歷史記錄,因爲它應該...
什麼發生的第一?鏈接導航或歷史更改?
我很想得到一個解釋。

回答

0

據我所知,在Firefox和Chrome中進行測試時,導航到當前頁面的鏈接不會修改瀏覽器歷史記錄。這兩種瀏覽器似乎都將其視爲「更新」而非導航。

這意味着您的第二個示例將有效地替換當前歷史記錄狀態兩次(一次使用javascript,然後再使用默認導航)。

這是我用來測試的代碼。評論/取消註釋replaceState以查看差異(沒有)。注意:我發現開啓Persist in Firebug可以讓我的控制檯日誌在導航過程中不被清除,這很有幫助。

<a href="./page1.html" onclick="func(event)">page 1</a> 
<script type="text/javascript"> 
function func(event) { 
    console.log("before: " + window.history.length); 
    //window.history.replaceState(null, '', "./page1.html"); 
    console.log("after: " + window.history.length); 
} 
onload = function() { console.log("load: " + window.history.length);} 
</script> 

我一直無法找到任何引用爲什麼瀏覽器以這種方式工作。不過,使用第一個示例進行驗證非常容易。點擊鏈接20次;您的後退按鈕將保持禁用狀態。

更新使用兩頁

page0.html

<a href="./page1.html" onclick="func(event)">page 1</a> 
<script type="text/javascript"> 
function func(event) { 
    console.log("before: " + window.history.length); 
    window.history.replaceState(null, '', "./page1.html"); 
    console.log("after: " + window.history.length); 
} 
onload = function() { console.log("load: " + window.history.length);} 
</script> 

page1.html

Page 1 
<script type="text/javascript"> 
onload = function() { console.log("load: " + window.history.length);} 
</script> 

這裏的點擊鏈接

load: 1   page0.html (line 8) 
before: 1   page0.html (line 4) 
after: 1   page0.html (line 6) 
load: 1   page1.html (line 3) 
load: 1   page1.html (line 3) 

當我在控制檯中看到我所說的NK正在發生的事情:

  1. 用戶點擊鏈接
  2. func
  3. 當前歷史狀態被替換page1.html
  4. 瀏覽器 「向下,」 到page1.html,頁面已經是(步驟3)但將其視爲刷新,因爲它是相同的頁面。
+0

詹姆斯,只要主播具有相同的當前頁面的href,你是對的。但是我正在談論主播引用其他頁面的情況。你可以再次使用其他網址的錨點進行這些測試嗎?你得到了什麼?你認爲這種行爲的原因是什麼? – Naor

+0

我明白你的意思了。我用兩頁更新了答案。基於測試,我認爲它基本上是一樣的事情發生,無論它是一頁還是兩頁。 –

+0

男人,你是最棒的。 – Naor