检测 URL 中的后退按钮/哈希更改 [英] Detecting Back Button/Hash Change in URL

查看:25
本文介绍了检测 URL 中的后退按钮/哈希更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在 http://ritter.vg 上设置了我的新主页.我正在使用 jQuery,但使用非常少.
它使用 AJAX 加载所有页面 - 我将它设置为允许通过检测 URL 中的哈希值来添加书签.

I just set up my new homepage at http://ritter.vg. I'm using jQuery, but very minimally.
It loads all the pages using AJAX - I have it set up to allow bookmarking by detecting the hash in the URL.

 //general functions
 function getUrl(u) {
      return u + '.html';
 }
 function loadURL(u)    {
      $.get(getUrl(u), function(r){
                $('#main').html(r);
           }
      );
 }
 //allows bookmarking
 var hash = new String(document.location).indexOf("#");
 if(hash > 0)
 {
      page = new String(document.location).substring(hash + 1);
      if(page.length > 1)
        loadURL(page);
      else
        loadURL('news');
 }
 else
      loadURL('news');

但是我无法让后退和前进按钮工作.

But I can't get the back and forward buttons to work.

有没有办法在不使用 setInterval 循环的情况下检测何时按下后退按钮(或检测何时哈希更改)?当我尝试使用 0.2 秒和 1 秒超时的那些时,它锁定了我的 CPU.

Is there a way to detect when the back button has been pressed (or detect when the hash changes) without using a setInterval loop? When I tried those with .2 and 1 second timeouts, it pegged my CPU.

推荐答案

使用 jQuery hashchange 事件 插件代替.关于完整的 ajax 导航,请尝试使用 SEO 友好的 ajax.否则,您的页面在具有 JavaScript 限制的浏览器中不会显示任何内容.

Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.

这篇关于检测 URL 中的后退按钮/哈希更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆