-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
102 lines (84 loc) · 3.03 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="todolist.css" rel="stylesheet">
<title>待办清单</title>
</head>
<body>
<header>
<h1>待办清单</h1>
<section>
<label for="add">要做些什么呢?</label>
<br>
<input id="add" type="text" placeholder="添加待办" required="required"></input>
</section>
</header>
<section>
<h2>正在进行中 <span id="todocount">0</span></h2>
<ol id="todolist"></ol>
</section>
<footer>今天又是元气满满的一天!</footer>
<!-- js -->
<script>
// 获取对象
const add = document.querySelector("#add");
const todolist = document.querySelector("#todolist");
const todocount = document.querySelector("#todocount");
const todos = JSON.parse(localStorage.getItem("todos")) || [];
// 初始化渲染
render();
// 添加事件监听
add.addEventListener('keydown', keydownHandler);
todolist.addEventListener("click", clickHandler);
todolist.addEventListener("change", changeHandler);
// 新增待办事件处理函数---enter
function keydownHandler(e) {
if (e.key === "Enter" && add.value.trim() !== "") {
todos.push(add.value);
localStorage.setItem("todos", JSON.stringify(todos));
add.value = "";
render();
} else {
return;
}
}
// 完成待办事件处理函数---click
function clickHandler(e) {
if (e.target.tagName !== "BUTTON") {
return;
} else {
// 通过li和ol获取其索引
let index = Array.from(todolist.children).indexOf(
e.target.parentNode
);
todos.splice(index, 1);
render();
}
}
// 修改待办事件处理函数---change
function changeHandler(e) {
let index = Array.from(todolist.children).indexOf(
e.target.parentNode
);
todos.splice(index, 1, e.target.value);
render();
}
// 渲染函数
function render() {
// 先删完
todolist.replaceChildren();
// 后更新
todocount.innerText = todos.length;
localStorage.setItem("todos", JSON.stringify(todos));
todos.forEach((content) => {
let item = document.createElement("li");
item.innerHTML = `<input type="text" value="${content}"></input><button class="delbtn">完成</button>`;
todolist.appendChild(item);
});
}
</script>
</body>
</html>