PHP Ajax动态列表的后退操作——保存列表内容和点击位置

版权声明:本文为博主原创文章,随便转载,但是请注明出处。 https://blog.csdn.net/sbdx/article/details/77836339

需求

列表页是ajax动态加载的,每次点击进入查看后返回,会丢失之前的位置,并且列表需要重新加载一次。

思路

绑定点击事件,点击的时候获取当前位置和列表HTML,存入sessionStorage。
后退的时候要判断是否从前一个页面返回的,这里就用到 **history.replaceState**

代码

//绑定事件
$('#list a').live('click',function(e){
    history.replaceState({}, document.title, location.href+"&history=-1");//写入标志位
    var _scrollTop = $("body").scrollTop();
    var _bodyHeight = $("body").height();
    sessionStorage.setItem('list',$('#list').html());
    sessionStorage.setItem('scrolltop',_scrollTop);
    sessionStorage.setItem('bodyheight ',_bodyHeight);
});

if(window.location.search.indexOf('history=-1') > 0)//检测标志位
{
    $('#list').html(sessionStorage.getItem('list'));
    $("body").height(sessionStorage.getItem('bodyheight'));
    $("body").scrollTop(sessionStorage.getItem('scrolltop'));
    history.replaceState({}, document.title, location.href.replace('&history=-1',''));//还原真实路径
}
else
{
    //不是后退的则加载
    ajaxdata(1);
}

参考

  1. ajax与HTML5 history pushState/replaceState实例 « 张鑫旭-鑫空间-鑫生活
  2. pjax

猜你喜欢

转载自blog.csdn.net/sbdx/article/details/77836339