微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – HTML5 / jQuery:pushState和popState – 深层链接?

首先,我似乎无法确定pushState函数中的第一个参数是什么?我传递给它的是什么?我只想在滚动页面时更改网址.我正在查询视口中当前元素的ID,其ID也应该是url中的链接.这适用于下面的代码.
var currentHash,url;

    if (history && history.pushState) {

        $(window).scroll(function() {
            hash = $('.layer:in-viewport').attr('id');
            catHash = $("#"+hash).parent('section').attr('id');

            var data = "nothing";

            if ( catHash != undefined )
                url = "/" + catHash + "/" + hash;
            else
                url = "/" + hash;

            if ( currentHash != hash ) {

                window.history.pushState(data,hash,url);

            }

            currentHash = hash;

        });

    }

现在我有两个问题:

1.)现在,当我滚动浏览页面时,地址栏中的URL会成功更改.我最初加载页面时如何查询地址栏中的url / hash.所以想象我现在有一个像www.url.com/deep这样的链接我想找出什么/深?我只需要查询整个top.location并将其拆分为每个“/”吗?我的意思是这些链接实际上不存在,那么在调用我使用pushState函数操作的url时如何避免使用404页面

2.)如何在单击后退按钮时找到地址栏中的最后一次更改?所以我想在点击浏览器后退按钮时找到/深,这样我就可以回到页面上的那个位置.我想这可能与popstate有关,但我无法找到方法

谢谢您的帮助!

更新:

window.history.pushState("test",url);

$(window).bind('popstate',function(event){
        console.log(event.data);
    });

这总是空的.这不应该返回“测试”吗?

解决方法

what the first parameter in the pushState function is for?

the documentation

state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state,a popstate event is fired,and the state property of the event contains a copy of the history entry’s state object.

因此,当您返回该状态时,它会返回您选择的一组数据.

Right Now the url in the addressbar changes successfully when I scroll through my page. How can I query the url/hash in the addressbar when I initially load the page.

查看位置对象…但您不需要.您可以(并且应该)填充页面服务器端.这是pushState的优势之一,如果JavaScript不可用并且服务器端回退顺利集成,则链接仍然有效.

How can I find out the last change in the addressbar when clicking the back button?

添加一个事件侦听器(查找popState事件),并且您在其中存储的数据将在事件对象上可用. MDN has an example

原文地址:https://www.jb51.cc/jquery/150741.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐