JSFiddle - React, Tailwind, and code Playground
by redky
HTML
<a href="1.html">test 1</a>
<a href="2.html">test 2</a>
<a href="3.html">test 3</a>
<a href="4.html">test 4</a>
JavaScript
// 页面刷新/back/go/forward 时触发.
window.onpopstate = function ( e ) {
console.log( e, e.state );
// length: 总 history 长度.
// state: 当前状态.
console.log( history.length, history.state );
};
var links = document.querySelectorAll( 'a' );
for ( var i = 0, l = links.length; i < l; i++ ) {
(function (i) {
var link = links[i];
link.onclick = function (e) {
console.log( 'href: ', this.href );
// 更新 url, 但是不刷新页面.
// 支持后退. 向浏览器历史中写数据.
if ( i < 3 ) {
history.pushState( {
page: i
}, i, this.href );
}
else {
// 替换当前状态.
history.replaceState( {
page: i
}, i, this.href );
}
e.preventDefault();
};
})(i);
}