【问题标题】:Refresh with back button when using anchor [duplicate]使用锚点时使用后退按钮刷新[重复]
【发布时间】:2013-01-05 20:36:10
【问题描述】:

可能重复:
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。

我看到了关于这个主题的不同问题,但我没有找到解决方法。

感谢您的帮助。

【问题讨论】:

  • 听起来您正在尝试更改浏览器的基本行为。 “刷新”刷新页面,“返回”返回。应该保持这种状态。
  • 如果您想使用fragment identifiers称为哈希标签)来导航您的网站,那么您应该利用History API
  • HTML 不允许在元素中输入元素。

标签: javascript jquery ajax html


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我刚刚找到了实现这一点的方法。我正在使用 onhashchange 功能。这是我的代码:

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

    所以当我按下返回按钮时,哈希消失并且页面重新加载。

    谢谢大家的提示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-10
      • 2019-03-29
      • 1970-01-01
      • 2021-04-28
      • 2012-02-22
      • 2015-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多