停止在hashchange上触发popstate [英] stop firing popstate on hashchange

查看:145
本文介绍了停止在hashchange上触发popstate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用History API并使用push和pop状态。我想在某些情况下停止popstate事件,我只将哈希附加到URL。例如,在某些情况下点击锚点它会将附加到URL并立即触发popstate)我想避免所有场景 #somehasvalue 附加到URL并停止弹出状态。我正在使用查询参数维护URL,我没有任何情况需要在URL中使用触发popstate事件。

I am working with the History API and using push and pop state. I want to stop the popstate event from firing in some scenario where I am only appending the hash to URL. for example in some cases on click of anchor it appends # to the URL and popstate is immediately fired) I want to avoid all the scenarios where # or #somehasvalue is appended to the URL and stop popstate from firing. I am mainitaing the URL's with query parameters and I do not have any scenario where I need the popstate event to fire with # in the URL.

这是我的代码。

if (supportsHistoryApi()) {

    window.onpopstate = function (event) {
    var d = event.state || {state_param1: param1, state_param2: param2};                       
    var pathName = window.location.pathname,
        params   = window.location.search;

    loadData(event, pathName + params, d.state_param1, d.state_param2);

}


推荐答案

目前为止因为我发现你无法阻止popstate开火。

As far as I found you cannot stop the popstate from firing unfortunately.

你可以做的是检查 event.state 对象。在散列更改时,这将为null。
所以我建议添加一个

What you can do is check for the event.state object. That will be null on a hash change. So I'd suggest adding a

if(event.state === null) {
   event.preventDefault();
   return false;
}

一开始就给你的popstate事件处理程序。
我认为这是防止在哈希值发生变化时触发popstate处理代码的最佳方法,但我有兴趣知道是否还有其他解决方案。

To your popstate event handler at the very beginning. I think that's the best way to prevent firing of the popstate handling code on your side when the hash changes, but i'd be interested to know if there are other solutions.

这篇关于停止在hashchange上触发popstate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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