写案例的时候碰巧用到了,把用到的两个对象方法记一下
一、History对象
History 对象包含用户(在浏览器窗口中)访问过的 URL。
History 对象是 window 对象的一部分,可通过 window.history 属性对其进行访问。
属性:length -- 返回浏览器历史列表中的 URL 数量。
方法
back()
history.back():表示页面往后退一步,与单击后退按钮的执行操作一样
go()
history.go(参数number/url):加载历史列表中的某个具体的页面。
参数为正数,如go(1),表示页面向前走一步
参数为负数,如go(-1),表示页面后退一步
参数为字符串,如go(url),前往指定地址
如:window.history.go(1) //当前页面向前走一步
二、location对象
reload()方法
location.reload(): 重新载入当前文档(刷新当前页面)
如:window.location.reload()
href属性
返回一个完整的URL
location.href = url地址
如:window.location.href = 'http://www.baidu.com'
如:window.location.href = url.value 给到的字符串要有http://,不然会以一个字符串去拼接当前的url
三、举例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="button" value="前进" id="prev">
<input type="button" value="后退" id="back">
<input type="button" value="刷新" id="reload">
<!-- url输入地址 -->
<input type="text" id="url">
<input type="button" value="跳转" id="go">
<p>
<input type="button" value="百度" id="baidu">
<input type="button" value="新浪" id="xinlang">
</p>
<script>
// 使用history对象和location对象
//history 可以实现页面的跳转
document.querySelector('#prev').addEventListener('click', () => {
window.history.go(1) //history.go 表示网页往前走一个
})
document.querySelector('#back').addEventListener('click', () => {
window.history.back() //history.back 表示网页往回走一个
})
document.querySelector('#reload').addEventListener('click', () => {
window.location.reload() //location.reload() 刷新
})
//获取url地址
let url = document.querySelector('#url')
//给跳转按钮绑定事件
document.querySelector('#go').addEventListener('click', () => {
window.location.href = url.value
})
//给百度和新浪绑定
document.querySelector('#baidu').addEventListener('click', () => {
window.location.href = 'http://www.baidu.com'
})
document.querySelector('#xinlang').addEventListener('click', () => {
window.location.href = 'http://www.sina.cn'
})
</script>
</body>
</html>