当前位置:首页 > 编程笔记 > 正文
已解决

单页面路由跳转之hash模式

来自网友在路上 185885提问 提问时间:2023-10-31 03:47:20阅读次数: 85

最佳答案 问答题库858位专家为你答疑解惑

hash模式

hash模式主要通过监听URL地址的哈希值的变化来实现页面更新

function routeHandle() {let appElm = document.querySelector('#app')let hash = window.location.hash.slice(1)switch (hash) {case '':case '/':case '/home':appElm.innerHTML = `<h1>Home</h1><button id="toListBtn">to list</button>`bindEvent()breakcase '/list':appElm.innerHTML = `<h1>List</h1><button id="toHomeBtn">to home</button>`bindEvent()breakdefault:appElm.innerHTML = `<h1>404</h1>`break}
}window.addEventListener('hashchange', routeHandle, false)

完整代码

<body><div id="app"></div>
</body>
function routeHandle() {let appElm = document.querySelector('#app')let hash = window.location.hash.slice(1)switch (hash) {case '':case '/':case '/home':appElm.innerHTML = `<h1>Home</h1><button id="toListBtn">to list</button>`bindEvent()breakcase '/list':appElm.innerHTML = `<h1>List</h1><button id="toHomeBtn">to home</button>`bindEvent()breakdefault:appElm.innerHTML = `<h1>404</h1>`break}
}function toListBtnHandle() {window.location.hash = '#/list'
}function toHomeBtnHandle() {window.location.hash = '#/'
}function bindEvent() {let toListBtnElm = document.querySelector('#toListBtn')let toHomeBtnElm = document.querySelector('#toHomeBtn')toListBtnElm && toListBtnElm.addEventListener('click', toListBtnHandle, false)toHomeBtnElm && toHomeBtnElm.addEventListener('click', toHomeBtnHandle, false)
}window.addEventListener('hashchange', routeHandle, false);(() => {routeHandle()
})()
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"单页面路由跳转之hash模式":http://eshow365.cn/6-28250-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!