当地址栏的hash值变化后,触发hashchange事件,从而改变页面数据
init: 初始化,window对象绑定hashchange监听
reloadPage: hashchange触发后的回调事件
map: hash值的配置与回调事件
/**
* 监听hash值实现单页面刷新
* init: 初始化,window对象绑定hashchange监听
* reloadPage: hashchange触发后的回调事件
* map: hash值的配置与回调事件
* **
* time: 2021/10
* sub: private
* version: 1.0
*/
(function () {
const Router = function () {
this.routers = {}
this.curUrl = ''
}
Router.prototype.init = function () {
window.addEventListener('hashchange', this.reloadPage.bind(this))
}
Router.prototype.reloadPage = function () {
this.curUrl = location.hash.substring(1) || '/'
this.routers[this.curUrl]()
}
Router.prototype.map = function (key, callback) {
this.routers[key] = callback
}
window.mRouter = Router
})()
<a href="#/">index</a>
<a href="#/game">game</a>
let router = new mRouter()
router.init()
router.map('/', function() {
// Do something here
console.log('index')
})
router.map('/game', function() {
// Do something here
console.log('game')
})
本文介绍了如何通过监听hashchange事件,实现在JavaScript中基于URL片段标识符的单页面应用(SPA)的无刷新导航。通过`Router`类实现初始化监听、路由映射和页面内容的动态更新,适用于现代Web开发中前端路由控制。
2493

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



