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

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

问题描述

我使用Ajax和哈希进行导航。有没有一种方法来检查 window.location.hash 变这样了?

I am using Ajax and hash for navigation. Is there a way to check if the window.location.hash changed like this?

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

它的工作原理,如果我签了文件加载时。 但是,如果我有#hash导航的时候我preSS浏览器上的后退按钮它不工作,(所以我从胡说#456跳等等#123)。它显示的地址框内,但我不能用JavaScript抓住它。

It works if I check it when the document loads. 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). 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的让你使用它的事件系统收听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 ..
});

在这里的好处是,你可以写code,这并不需要,甚至担心hashchange的支持,然而,你需要做一些神奇的,在一个有些不太知名的jQuery功能的jQuery特别活动的。

通过这个功能,你根本弄运行一些设置$ C $下任何情况下,第一次有人尝试使用该事件以任何方式(如绑定到事件)。

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).

在此设置code,你可以检查本地浏览器的支持,如果浏览器本身并不实现这一点,你可以设置一个计时器轮询的变化,并触发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.

这完全解除绑定您的code从需要了解这种支持的问题,这样的一个特殊事件的实现很简单(要得到一个简单的98%的工作版本),但为什么这样做的when别人已经的。

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天全站免登陆