history.pushState()并单击后退/前进按钮 [英] history.pushState() and clicking back/forward button

查看:491
本文介绍了history.pushState()并单击后退/前进按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,可以在ajax加载时更改网址

This is my code to change url on ajax load which works

$.ajax({
  url: url,
  success: function (data) {
  $(selector).html(data);
    var title = data.match("<title>(.*?)</title>")[1]; // get title of loaded content   
    window.history.pushState( {page : 0} , document.title, window.location.href ); // store current url.    
    window.history.pushState( {page : 1} , title, url ); // Change url.
    document.title = title; // Since title is not changing with window.history.pushState(), 
    //manually change title. Possible bug with browsers.
    window.onpopstate = function (e) {
        window.history.go(0);
    };
  }
});

当我单击后退时,正在加载上一页.如果我再次单击,将什么也没有发生.再单击一次将转到第一页.经过测试后,每次加载Ajax时,后退按钮中都有2个相同的页面

when i click back , previous page is loading. And if i click again nothing happen. And one more click it will goto first page. After some testing i found , there are 2 same page in back button ,on each ajax loading

我也需要一个代码来获取单击前进按钮时的历史记录

推荐答案

主持人已删除我的帖子,原因是我确实只提供了一些小片段代码以寻求帮助.

Moderators have removed my post, for the reason that I really given little scraps of code to try to help.

但是我还是会举一个例子:

But still I will try to give an example:

假设您的代码是由onclick事件触发的.

Suppose you have this code is triggered by the event onclick.

$(function() {
    function load(url, push) {
        $.ajax({
            url: url,
            success: function (data) {
                var title = data.match("<title>(.*?)</title>")[1];
                document.title = title;
                if (push) {
                    history.pushState(null, title, url);
                }
            }
        });
    }

    $(document).click(function(e) {
        if (e.target.nodeName === 'A') {
            var url = $(e.target).attr('href');
            if (url.indexOf('#') !== 0) {
                load(url, true);
                e.preventDefault();
            }
        }
    });

    $(window).bind('popstate', function(e) {
        load(window.location.href, false);
    });
});

这篇关于history.pushState()并单击后退/前进按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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