2015-11-20 27 views
0

我正在ASP.NET MVC3 Web應用程序中工作,我的問題如下:我想檢測使用URL變化:onhashchange事件不檢測「/ Home/Index」和「/」之間的變化 - ASP.NET MVC3

window.onhashchange = function (event) { 
    //some stuff... 
}; 

和它的作品完美...但是,它完美的作品,而在URL中總是出現:

的 'localhost:[端口] /首頁/索引'

或在某些情況下,網址更改爲:

的 'localhost:[端口] /首頁/索引#'

當用戶更改URL(例如,他刪除' /首頁/指數「)時,頁面重新加載(網址爲」 本地主機:端口]/「),但是當用戶按下後退按鈕,然後再返回到」 /首頁/索引'onhashchange事件 沒有按沒有發現這種變化。爲什麼? '/首頁/索引'和'/'是一樣的嗎?

回答

0

哈希值是之後的#符號在url中。

如果當前的網址是:

http://localhost:12345/Home/Index#chapter-1 

,並有人點擊這樣一個鏈接:<a href="#chapter-2">Chapter 2</a>然後URL的散列部將改變導致window.onhashchange被解僱。導航到另一個頁面不會觸發onhashchange事件,因爲散列在新頁面上沒有更改。

window.onhashchange = function(e) { 
 
     var log = document.getElementById("log"); 
 

 
     log.innerText = "Event: Hash changed " + location.hash; 
 

 
     window.setTimeout(function() { 
 
     log.innerText = "Event: "; 
 
     }, 3000); 
 
    }
<div id="log">Event:</div> 
 

 
<ul> 
 
    <li><a href="#chapter1">Change hash to chapter 1</a></li> 
 
    <li><a href="#chapter2">Change hash to chapter 2</a></li> 
 
    <li><a href="#">Change hash to nothing</a></li> 
 
    <li><a href="#" onclick="location.reload()">reload page</a></li> 
 
</ul>

+0

我有一個概念上的錯誤...謝謝! –

相關問題