版权声明:本文为博主原创文章,未经博主允许不得转载。
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);
 }

在这里插入图片描述

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐