原生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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值