原生JavaScript控制页面跳转的几种方式
在开发一些简单的页面,不需要复杂的单页面应用(SPA)功能的时候。可以使用原生JavaScript 的跳转即可满足需求。另外在处理一些需要直接与服务器进行交互的表单提交后跳转,或者在某些浏览器兼容性要求较高的场景下,原生 JavaScript 的跳转方式更加稳定可靠。
正文开始
这里本地创建两个html文件进行演示,index.html 和home.html
window.location.href
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>index页面</title>
</head>
<body>
<div>
<h2>index页面---原生js跳转的几种方式</h2>
<button onclick="nav1()">href</button>
</div>
<script>
function nav1(){
window.location.href='./home.html'
}
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>home页</title>
</head>
<body>
<div>
<h2>home页</h2>
</div>
</body>
</html>
window.location.assign
<button onclick="nav2()">assign</button>
<script>
function nav2(){
window.location.assign('./home.html')
}
</script>
assign效果等同于上面window.location.href
window.location.replace
replace不会生成历史记录,也就是说使用这种方式在浏览器中跳转到目标页面是无法返回的
<button onclick="nav3()">replace</button>
<script>
function nav3(){
window.location.replace('./home.html')
}
</script>
window.open
open方法默认是以当前页面打开新页面的,需要新窗口打开则传入第二个参数 _blank,默认是当前窗口打开
<button onclick="nav4()">open</button>
<script>
function nav4(){
window.open('./home.html','_blank')
}
</script>
history
history对象是浏览器历史记录的接口,你可以使用它来在用户的浏览历史中前进或后退,也可以跳转到指定的历史记录位置。
history.go() 方法可以接受一个整数参数,正数表示向前跳转指定的步数,负数表示向后跳转指定的步数。传入0 相当于 location.reload() 重新加载页面。传入参数大于历史记录的话则不会有任何效果。
history.back() 相当于 history.go(-1)
history.forward() 相当于 history.go(1)