当前位置: 首页 > article >正文

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


http://www.kler.cn/a/593108.html

相关文章:

  • git tag常用操作
  • Springboot项目打包成war包
  • AJAX PHP:深入理解与实际应用
  • 基于SpringBoot + Vue 的药店药品信息管理系统
  • 基于Spring Boot的本科生交流培养管理平台的设计与实现(LW+源码+讲解)
  • QT--按键事件与定时器事件
  • 【一起来学kubernetes】15、Job使用详解
  • Node.js 中使用 RabbitMQ
  • linux-----------------指令下集
  • 微服务的网关配置
  • springboot集成xxl-job
  • YOLOv8模型修改与CA注意力机制详解
  • Qwen2-Audio:通义千问音频大模型技术解读
  • FPGA实现LED流水灯(开发板为DE2-115)
  • C#:深入理解Thread.Sleep与Task.Delay
  • Debezium + Kafka-connect 实现Postgres实时同步Hologres
  • Word 小黑第40套
  • Error: The project seems to require pnpm but it‘s not installed.
  • Centos7.6单机部署Kafka
  • 数据库:一文掌握 Oracle 的各种指令(Oracle指令备忘)