使用锚点时使用后退按钮刷新

时间:2013-01-05 20:36:10

标签: javascript jquery ajax html5

  

可能重复:
  Handle URL anchor change event in js
  How to do awesome refreshless page changes like GitHub

在我的应用程序中,我使用这个非常简单的代码添加标签:

         <a href='#test'> <input type='submit'></input>

我希望按下后退按钮时页面会刷新。目前,它只是从www.mysite.com/#test到www.mysite.com。

我在这个主题上看到了不同的问题,但我没有找到如何实现这一目标。

感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

一种简单的方法是等待哈希更改事件发生,然后对其做出反应。每当#更改时,将调用该函数,如果散列为空,则将重新加载该页面。

window.addEventListener('hashchange', function() {
  console.log(window.location.hash);

  if('' === window.location.hash) {
    console.log('reload');
    //window.location.reload();
  }
});

http://jsfiddle.net/kcKLE/1/

我建议使用类似jQuery的库来处理事件,因为addEventListener在任何浏览器中都不起作用。 (你好IE) https://developer.mozilla.org/en/docs/DOM/element.addEventListener

如果你需要更高级的东西,还有一个历史api。 https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history

答案 1 :(得分:0)

我刚刚找到了如何实现这一目标。我正在使用onhashchange功能。这是我的代码:

    document.body.setAttribute("onhashchange", "update()");
         function update() {
            if('' === window.location.hash) {
                 window.location.reload();
          }

      };

因此,当我按下后退按钮时,哈希消失,页面重新加载。

感谢大家提示。

相关问题