HTML5 History API - 不要在首页加载时触发 window.onpopstate 事件
使用 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);
完整的代码在这里:
我在这里遇到的问题是我不想触发 w.onpopstate< /code> 页面第一次来自服务器时的事件。
我想这样做的原因是我想在服务器端填充页面,并且我不希望客户端代码执行此操作。如果我删除 w.onpopstate
事件,我将无法捕获 history.go()
事件。
有什么办法可以解决这个问题吗?
With HTML5 History API, I created something like below:
(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);
The complete code is here:
The problem I have here is that I do not want to fire the w.onpopstate
event at the first time page comes from the server.
The reason I would like to do this is that I would like to fill the page at the server side and I do not want client side code to do that. If I remove w.onpopstate
event, I won't be able to catch history.go()
events.
Is there any way to solve this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一个非常简单的方法是:
这意味着第一次触发
onpopstate
事件时,您的函数将设置为事件处理程序(替换当前处理程序),从而有效地创建一个 noop 表示事件在页面加载时运行。A very simple approach would be this:
This means that the first time the
onpopstate
event fires, your function is set to the event handler (replacing the current handler), effectively creating a noop for when the event runs on page load.