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

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

被折叠的 条评论
为什么被折叠?



