js编程思路
- 监听input事件,匹配按键为key,找出对应的value值.存入变量中,创建一个对象添加变量值,把函数中的对象添加到全局中的todoList数组中,并渲染调用.
inputDom.onkeydown = function (event) {
if (event.key === "Enter") {
var value = inputDom.value
var objItem = {
content: value,
isDone: false
}
todoList.push(objItem)
console.log(event)
render(todoList)
}
}
- 写一个创建列表的方法,按照input事件之后
// 渲染网页 参数为todoList数组对象
function render(todoList) {
localStorage.todoList = JSON.stringify(todoList)
// 将对象转换为json格式存入本地存储
doingListDiv.innerHTML = " "
doneListDiv.innerHTML = " "
// 清空列表元素
console.log(1)
todoList.forEach(function (item, index) {
//item为列表对象,index为列表排序数字
var todoItem = document.createElement("div")
todoItem.className = "todoItem"
if (item.isDone) {
//按照isDone属性值为false,修改为true后执行的html元素添加行为
todoItem.innerHTML = `<input type="checkbox" checked="checked" data-index="${index}">
<div class="content">`+ item.content + `</div>
<div class="del" data-index="${index}">删除</div>`
doneListDiv.appendChild(todoItem)
} else {
//如果是刚创建的item,其中的isDone属性值为false,创建元素节点添加进html结构中
todoItem.innerHTML = `<input type="checkbox" data-index="${index}">
<div class="content">`+ item.content + `</div>
<div class="del" data-index="${index}">删除</div>`
doingListDiv.appendChild(todoItem)
}
})
}
- input元素状态发生修改执行的函数---onchange
doingListDiv.onchange = function (e) {
//获取doingList元素绑定事件写方法
console.log(e)
// 用css自定义属性标记index值,然后修改todoList下标,修改对应的列表(改为true==进去done列表)
var index = parseInt(e.target.dataset.index)
console.log(index)
todoList[index].isDone = true
render(todoList)
}
// 用css自定义属性标记index值,然后修改todoList下标,修改对应的列表(改为false==进去doing列表)
doneListDiv.onchange = function (e) {
console.log(e)
var index = parseInt(e.target.dataset.index)
console.log(index)
todoList[index].isDone = false
render(todoList)
}
- 删除按钮绑定事件,事件代理给父元素main
mainDiv.onclick = function (e) {
if (e.target.className == "del") {
console.log(e)
var index = parseInt(e.target.dataset.index)
todoList.splice(index, 1)
render(todoList)
}
}
- 函数e打印输出内容
Event {isTrusted: true, type: "change", target: input, currentTarget: div.list, eventPhase: 3, …}
bubbles: true
cancelBubble: false
cancelable: false
composed: false
currentTarget: null
defaultPrevented: false
eventPhase: 0
isTrusted: true
path: (9) [input, div.todoItem, div.list, div.todo.doing, div.main, body, html.iphone.lt640.lt960.lt1200, document, Window]
returnValue: true
srcElement: input
target: input
timeStamp: 18895.4650000087
type: "change"
__proto__: Event
- 本地存储,todoList对象转换字符串格式
localStorage.todoList = JSON.stringify(todoList)