在使用onPopState和pushState时,我应该使用什么j来处理后退按钮单击 [英] What js should I use to handle back button clicks while using onPopState and pushState

查看:438
本文介绍了在使用onPopState和pushState时,我应该使用什么j来处理后退按钮单击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用pushState更改网站的网址:

I'm using pushState to change the url of a website:

history.pushState("", "info", "/info");

哪个效果很好,但现在后退按钮不起作用。我相信我需要使用遍历历史堆栈的onPopState编写自己的后退和前进按钮行为并呈现相应的页面。诀窍是当后退为空时,它应该做后退按钮通常会做的事情(在用户进入我的网站之前返回页面)。

Which works great, but now the back button doesn't work. I believe I need to write my own back and forward button behavior using onPopState that goes through the history stack and renders the appropriate page. The trick is that when "back" is Null, it should do the thing that the back button normally would do (go "back" to the page before the user entered my site).

这看起来很标准,有没有我可以使用的食谱/标准代码?

This seems like pretty standard behavior, is there a recipe / some standard code I could use?

推荐答案

啊我提出了一个解决方案,并不像我想象的那么难(基本上它只是使用url路径名来呈现正确的东西):

Ah I came up with a solution, not as hard as I thought (basically it just uses the url pathname to render the right stuff):

// Makes the back button work
window.onpopstate = function(event) {
    if (document.location.pathname == '/main') {
        $("#main").show();
        $("#info").hide();
        $("#settings").hide();
    }
    if (document.location.pathname == '/info') {
        alert('info');
        $("#main").hide();
        $("#info").show();
        $("#settings").hide();
    }
    if (document.location.pathname == '/settings') {
        alert('settings');
        $("#main").hide();
        $("#info").hide();
        $("#settings").show();
    }
};

这篇关于在使用onPopState和pushState时,我应该使用什么j来处理后退按钮单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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