在不触发hashchange事件的情况下更改哈希 [英] Change hash without triggering a hashchange event

查看:293
本文介绍了在不触发hashchange事件的情况下更改哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用哈希来动态加载内容。为了使后退按钮工作,我正在捕获哈希变化。但是有时我需要更改散列而不触发散列更改功能(例如,当页面被重定向到服务器端时,我需要在内容返回后更新散列。)

I'm using the hash to load content dynamically. To make the back button work I am capturing hash changes. However sometimes I need to change the hash without triggering the hash changed function (eg, when the page was redirected server side and I need to update the hash once the content has returned.)

我提出的最佳解决方案是取消绑定hashchange事件,进行更改然后重新绑定它。但是,由于这是异步发生的,我发现它重新绑定太快并仍然捕获哈希值。

The best solution I have come up with is to unbind the hashchange event, make the change and then rebind it. However, as this happens asynchronously, I am finding that it rebinds too quickly and still catches the hash change.

我的解决方案目前非常糟糕:重新绑定在setTimeout中。有没有人有更好的主意?

My solution at the moment is very poor: Rebinding in a setTimeout. Does anyone have a better idea?

    $(window).unbind( 'hashchange', hashChanged);
    window.location.hash  = "!" + url;
    setTimeout(function(){
        $(window).bind( 'hashchange', hashChanged);
    }, 100);


编辑:< br>
Amir Raminfar的建议促使我找到一个不需要超时的解决方案。
我添加了一个类变量


Amir Raminfar's suggestion prompted me to a solution that does not require a timeout. I added a class variable

_ignoreHashChange = false;

当我想静默更改哈希时,我这样做:

When I want to change the hash silently I do this:

_ignoreHashChange = true;
window.location.hash  = "!" + url;

并且散列更改事件执行此操作:

and the hash changed event does this :

function hashChanged(event){
    if(_ignoreHashChange === false){
        url = window.location.hash.slice(2);
        fetchContent(url);
    }
    _ignoreHashChange = false;
}


推荐答案

你可以拥有类似的功能这个:

You can have a function like this:

function updateHash(newHash){
  ...
  oldHash = newHash
}

然后在你的setTimeOut中你需要做

then in your setTimeOut you need to do

function(){
  if(oldHash != currenHash){
    updateHash(currenHash);
  }
}

所以现在你可以手动调用update hash并赢了不会被事件触发。您还可以在updateHash中使用更多参数来执行其他操作。

So now you can call update hash manually and it won't be triggered by the event. You can also have more parameters in updateHash to do other things.

顺便问一下,你看过jquery历史插件了吗? http://tkyk.github.com/jquery-history-plugin/

By the way, have you looked at the jquery history plugin? http://tkyk.github.com/jquery-history-plugin/

这篇关于在不触发hashchange事件的情况下更改哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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