繁体   English   中英

HTML5历史记录API - 不要在第一页加载时触发window.onpopstate事件

[英]HTML5 History API - Do not fire window.onpopstate event at the first page load

使用HTML5 History API,我创建了如下内容:

(function (d, w) {

    $(function () {

        $("#indicator").hide();

        if (typeof history.pushState !== 'undefined') { 

            $("#citylinks a").click(function (e) {
                history.pushState({ path: this.href }, '', this.href);
                act(this.href);
                e.preventDefault();
            });

            w.onpopstate = function (event) {
                act(d.location);
            };
        }

        function act(location) {

            $("#results").hide();
            $("#indicator").show();

            $.getJSON(location, function (data) {

                $("#results").html(data.result);
                $("#results").fadeIn();

                $("#indicator").hide();
            });
        }

    });

})(document, window);

完整的代码在这里:

https://github.com/tugberkugurlu/MvcMiracleWorker/commit/7c511f20678bbfe15462909c794eb323ce615372#diff-3

我在这里遇到的问题是,我不希望在第一次来自服务器的页面上触发w.onpopstate事件。

我想这样做的原因是我想填写服务器端的页面,我不希望客户端代码这样做。 如果我删除w.onpopstate事件,我将无法捕获history.go()事件。

有什么方法可以解决这个问题吗?

一个非常简单的方法是:

w.onpopstate = function () {
    w.onpopstate = function (event) {
        act(d.location);
    }
}

这意味着onpopstate事件第一次触发时,您的函数被设置为事件处理程序(替换当前处理程序),有效地在页面加载时运行事件时创建一个noop

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM