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

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

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.

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

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

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

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


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

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

_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;
}

2 个解决方案

#1


5

You can have a function like this:

你可以有这样的功能:

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

then in your setTimeOut you need to do

然后在你的setTimeOut中你需要做

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

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.

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

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

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

更多相关文章

  1. jQuery的$.getJSON方法在IE浏览器下失效的解决方案
  2. jQuery 事件绑定方法(bind hover toggle live.... )、删除事件方法
  3. JQuery UI datepicker在绑定到类时不起作用
  4. jQuery中的bind绑定事件与文本框改变事件的临时解决方法
  5. jQuery+EasyUI实现treegrid/datagride所绑定列只能够输入数字,且
  6. [置顶] JQuery datatables 使用Fixedcolumns固定列控件
  7. jQuery Ui Draggable在移动端浏览器不起作用解决方案
  8. 绑定和解除相同javascript函数的目的是什么?
  9. 使用HTML5验证时如何绑定到提交事件?

随机推荐

  1. PHP ZipArchive 实现压缩解压Zip文件
  2. brandhb.com 品牌回报网招聘php工程师
  3. php判断手机浏览还是web浏览,并执行相应的
  4. PHP变量类型+整型类型细节
  5. PHP中的替代语法
  6. 仅在LARAVEL或AJAX中提交表单时,无需用户
  7. JAVA/PHP/C#版RSA验签--转
  8. 十大最流行PHP框架排名
  9. 无法在phpmyadmin中打开一些表
  10. PHP联系表格给用户发送随机确认号码