六种js实现路由跳转方法

本文主要介绍了JS的六种路由跳转方法,包括页面跳转的window.location.href、hash跳转的window.location、pushState方法、replaceState方法以及window.onpopstate函数等,并提及了部分方法的实现效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版权声明:本文为博主原创文章,未经博主允许不得转载。
js路由跳转方法有很多,这里列出六种

<button onclick="routerWay()">页面路由跳转方法</button>
<button onclick="hashWay()">hash跳转方法</button>
<button onclick="backWay()">backWay方法</button>
<button onclick="pushState()">pushState方法</button>
<button onclick="replaceState()">replaceState方法</button>

刚开始页面效果为:在这里插入图片描述
方法一:页面跳转——window.location.href

function routerWay() {
   window.location.href = 'http://www.baidu.com';
}

效果为:
在这里插入图片描述
方法二:
hash跳转——window.location

function hashWay() {
	window.location = '#hash';
	 // hash变化时触发
	 window.onhashchange = function(){
	    //  console.log('current hash:', window.location.hash);
	 }
}

效果为:
在这里插入图片描述
方法三:

// 实现后退功能
function backWay() {
	// history.back();
	history.go(-1); 
}

在方法二效果的基础上实现效果为:
在这里插入图片描述
方法四:pushState方法

function pushState() {
 	history.pushState(null, null, '?path1');
}

实现效果为:
在这里插入图片描述
方法五:replaceState

function replaceState() {
	history.pushState(null, null, '?path2');
}

效果为:
在这里插入图片描述
方法六:window.onpopstate
该函数在点击红框中的左右箭头时会触发。

window.onpopstate = function(){
	console.log(window.location.href);
 }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值