<h2>historys</h2>
<a class=\"api a\">a.html</a>
<a class=\"api b\">b.html</a>
<h2>hash</h2>
<a class=\"hash a\">c.html</a>
<a class=\"hash b\">d.html</a>
// history
//注册路由
document.querySelectorAll(\'.api\').forEach(item => {
item.addEventListener(\'click\', e => {
e.preventDefault();
let link = item.textContent;
window.history.pushState({
name: \'api\'
}, link, link);
})
})
//监听路由
window.addEventListener(\'popstate\', e => {
console.log({
location: location.href,
state: e.state
})
})
// hash
//注册路由
document.querySelectorAll(\'.hash\').forEach(item => {
item.addEventListener(\'click\', e => {
e.preventDefault();
let link = item.textContent;
location.hash = link;
}, false)
})
//监听路由
window.addEventListener(\'hashchange\', e => {
console.log({
location: location.href,
hash: location.hash
})
}, false)
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。



