function History(input,ul){
this.input = document.querySelector(input)
this.ul = document.querySelector(ul)
this.historyData = new Set()
}
History.prototype.run = function(){
this.bindEvent()
this.getSession()
this.show()
}
History.prototype.bindEvent = function(){
const self = this
this.input.addEventListener('blur',function(){
if (!this.value) {
return
}
if (self.historyData.has(this.value)) {
self.historyData.delete(this.value)
}
self.historyData.add(this.value)
self.saveSession()
self.show()
})
}
History.prototype.show = function(){
this.ul.innerHTML = ''
for (const item of Array.from(this.historyData).reverse()) {
this.ul.innerHTML +=`<li>${item}</li>`
}
}
History.prototype.saveSession = function(){
const data = JSON.stringify(Array.from(this.historyData))
window.sessionStorage.setItem('history',data)
}
History.prototype.getSession = function(){
const data = window.sessionStorage.getItem('history')
this.historyData = new Set(JSON.parse(data))
}
const h = new History('[name=history]','.history')
h.run()
封装是真的爽翻了!!!