在 - window.location.hash - 改变? [英] On - window.location.hash - Change?

查看:36
本文介绍了在 - window.location.hash - 改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Ajax 和哈希进行导航.

I am using Ajax and hash for navigation.

有没有办法检查window.location.hash是否像这样改变了?

Is there a way to check if the window.location.hash changed like this?

http://example.com/blah#123http://example.com/blah#456

如果我在文档加载时检查它,它会起作用.

It works if I check it when the document loads.

但是如果我有基于 #hash 的导航,当我按下浏览器上的后退按钮时它不起作用(所以我从 blah#456 跳转到 blah#123).

But if I have #hash based navigation it doesn't work when I press the back button on the browser (so I jump from blah#456 to blah#123).

它显示在地址框中,但我无法用 JavaScript 捕捉到它.

It shows inside the address box, but I can't catch it with JavaScript.

推荐答案

真正做到这一点的唯一方法(以及 'reallysimplehistory' 如何做到这一点),是通过设置一个间隔来不断检查当前哈希,并比较它与之前的情况相反,我们这样做并让订阅者订阅一个更改的事件,如果哈希值发生更改,我们会触发该事件......这并不完美,但浏览器本身并不支持此事件.

The only way to really do this (and is how the 'reallysimplehistory' does this), is by setting an interval that keeps checking the current hash, and comparing it against what it was before, we do this and let subscribers subscribe to a changed event that we fire if the hash changes.. its not perfect but browsers really don't support this event natively.

更新以保持此答案新鲜:

Update to keep this answer fresh:

如果您正在使用 jQuery(现在对于大多数人来说应该是基础),那么一个不错的解决方案是使用 jQuery 为您提供的抽象,通过使用其事件系统来侦听 window 对象上的 hashchange 事件.

If you are using jQuery (which today should be somewhat foundational for most) then a nice solution is to use the abstraction that jQuery gives you by using its events system to listen to hashchange events on the window object.

$(window).on('hashchange', function() {
  //.. work ..
});

这里的好处是您可以编写甚至不需要担心 hashchange 支持的代码,但是您确实需要以鲜为人知的 jQuery 功能的形式做一些魔术jQuery 特殊事件.

The nice thing here is you can write code that doesn't need to even worry about hashchange support, however you DO need to do some magic, in form of a somewhat lesser known jQuery feature jQuery special events.

有了这个功能,你基本上可以为任何事件运行一些设置代码,第一次有人尝试以任何方式使用该事件(例如绑定到事件).

With this feature you essentially get to run some setup code for any event, the first time somebody attempts to use the event in any way (such as binding to the event).

在此设置代码中,您可以检查本机浏览器支持,如果浏览器未本机实现此功能,您可以设置一个计时器来轮询更改,并触发 jQuery 事件.

In this setup code you can check for native browser support and if the browser doesn't natively implement this, you can setup a single timer to poll for changes, and trigger the jQuery event.

这完全使您的代码无需理解此支持问题,这种特殊事件的实现是微不足道的(以获得简单的 98% 工作版本),但为什么要这样做 当其他人已经.

This completely unbinds your code from needing to understand this support problem, the implementation of a special event of this kind is trivial (to get a simple 98% working version), but why do that when somebody else has already.

这篇关于在 - window.location.hash - 改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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