- 案例只有添加和删除以及本地存储功能,利用es6class封装了一个功能类
<div class="box">
<button class="deleteBtn">删除</button>
<input type="text">
<button class="addBtn">添加</button>
<ul class="todos">
</ul>
</div>
.box {
width: 400px;
height: 600px;
border: 1px solid #ccc;
}
ul>li {
position: relative;
height: 30px;
line-height: 30px;
margin: 10px;
background: #ccc;
}
li input {
width: 20px;
height: 20px;
margin: 6px 20px 0 8px;
}
li span {
display: inline-block;
height: 30px;
vertical-align: top;
}
class Todos {
constructor(el) {
this.default = [
{id: 1,todo_name: '吃饭'},
{id: 2,todo_name: '睡觉'},
{id: 3,todo_name: '打豆豆'},
]
this.lists = this.getLocal() || this.default
this.addId = 4
this.element = el
}
add(item) {
if(item) {
this.lists.push({id: this.addId,todo_name: item})
this.setLocal()
this.addId ++
this.render()
}
}
delete(ids) {
let idarr = ids.split(',')
if(idarr.length) {
this.lists = this.lists.filter(item => {
return idarr.indexOf(String(item.id)) == -1;
})
this.setLocal()
this.render()
}
}
render() {
let temp = ''
this.lists.forEach(item => {
temp += ` <li data-id="${item.id}">
<input type="checkbox">
<span>${item.todo_name}</span>
</li>`
})
this.element.innerHTML = temp
}
setLocal() {
localStorage.setItem("list",JSON.stringify(this.lists))
}
getLocal() {
return JSON.parse(localStorage.getItem("list"))
}
}
let todos = document.querySelector('.todos')
let lis = todos.children
let addbtn = document.querySelector('.addBtn')
let deletebtn = document.querySelector('.deleteBtn')
let addval = document.querySelector('input[type="text"]')
let todolist = new Todos(todos)
todolist.render()
addbtn.addEventListener('click',function() {
todolist.add(addval.value)
})
deletebtn .addEventListener('click',function() {
let arr = Array.from(lis)
let arrid = []
arr.forEach(item => {
if(item.children[0].checked) {
arrid.push(item.getAttribute('data-id'))
}
})
todolist.delete(arrid.join(','))
})