十、history

十、history

10.1 history.forward

该方法会加载历史记录列表中的下一个URL

调用该方法等价于点击了前进按钮获取history.go(1)

10.2 history.back

该方法会加载历史记录列表中的前一个URL

调用该方法等价于点击了后退按钮获取history.go(-1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<a href="third.html">third.html</a>
<button id="pre">后退</button>
<button id="next">前进</button>
<script>
// 获取元素
var pre = document.getElementById("pre");
var next = document.getElementById("next");

// 添加点击事件
pre.onclick = function(){
// 调用 back
history.back();
}
next.onclick = function(){
// 调用 forward
history.forward();
}

UYUVVx.png

10.3 pushState

作用:用于添加新的历史记录

使用方式:

1
2
3
4
history.pushState(obj, title, url)
obj:数据对象
title:新的网页标题(一般省略)
url:新的网页url
1
history.pushState({username: "老王"}, null, "index.html#aaa");

UYUeIK.png

10.4 replaceState

作用:替换当前历史记录

使用方式:

1
2
3
4
history.replaceState(obj, title, url)
obj:数据对象
title:网页标题(一般省略)
url:新的url

pushStatereplaceState的区别:

1
2
pushState是添加新的历史记录
replaceState是替换当前历史记录
1
2
3
4
5
6
// 替换当前历史记录
history.pushState({username: "老王"}, null, "index.html#aaa");
history.pushState({username: "老李"}, null, "index.html#bbb");

// 替换当前历史记录
history.replaceState({username: "老张"}, null, "index.html#ccc");

原本打开页面应该显示bbb,然后替换当前历史记录,变为ccc,每次刷新都会增加一条历史记录

UYUKRe.png

点击查看

本文标题:十、history

文章作者:Mango

发布时间:2020年07月14日 - 13:18:56

最后更新:2020年07月14日 - 13:27:10

原始链接:https://mango185.github.io/post/6b0212c5.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------