[TOC]
一、简要回顾
- 首先,history是一个BOM对象,可以使用history.back()进行回退页面,或者是使用history.forward()进行前进。
这里主要使用的两个API,分别是history.pushState(data,title,url)和一个监听事件popstate,这个事件会在地址栏发生变化的时候发生。
二、实例
<body> <input type="text" id="search"> <button onclick="search()">搜索</button> <div class="main"></div> <script> render(data); </script> </body>
```javascript
const data = [{ "name": "HTML" }, { "name": "CSS" }, { "name": "JS" }, { "name": "TS" }, { "name": "NPM" }, { "name": "VUE" } ]; function search() { let value = document.getElementById("search").value; let obj = data.filter(function (ele) { if (ele.name.indexOf(value) > -1) { let res = ele.name; return res; } }); history.pushState({ "inpVal": value }, null, '#' + value); render(obj); }
function render(obj) {
let main = document.getElementsByClassName("main")[0];
let content = "";
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
const element = obj[key];
content += `<h1>${element.name}</h1>`;
}
}
main.innerHTML = content;
}
window.addEventListener("popstate", function (e) {
// console.log(e);
document.getElementById("search").value = e.state.inpVal;
let value = e.state.inpVal;
let obj = data.filter(function (ele) {
if (ele.name.indexOf(value) > -1) {
let res = ele.name;
return res;
}
});
render(obj);
});
window.addEventListener("hashchange", function (e) {
console.log(e);
})
</script>