onhashchange事件不检测“/ Home / Index”和“/”之间的变化 - ASP.NET MVC3

时间:2015-11-20 13:27:06

标签: javascript event-handling

我正在使用ASP.NET MVC3 Web应用程序,我的问题如下:我想使用以下方法检测URL更改:

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

并且它完美地工作......但是,它在网址中总是出现时效果很好:

  

'本地主机:[端口] /主页/索引'

或在某些情况下,网址更改为:

  

'localhost:[port] / Home / Index#'

当用户更改网址时(例如,他删除了' / Home / Index '),网页会重新加载(网址为' localhost:[port] / ')但当用户按下后退按钮并再次返回“ /主页/索引”onhashchange事件时 没有发现这种变化。为什么? ' / Home / Index '和' / '是一样的?

1 个答案:

答案 0 :(得分:0)

哈希是在网址中 #符号后的内容。

如果当前网址为:

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

并且有人点击了这样一个链接:<a href="#chapter-2">Chapter 2</a>然后网址的哈希部分会发生变化,导致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>