-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
102 lines (72 loc) · 2.3 KB
/
Copy pathscript.js
File metadata and controls
102 lines (72 loc) · 2.3 KB
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
const todoInput = document.querySelector("#todo-input");
const todoList = document.querySelector("#todo-list");
let todos = [];
// XSS 방어 . 속성 손상 방지 . 배열에는 원본 그대로 저장하되 Display시에 개입
function escapeHtml(str) {
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function todoInit() {
todos = JSON.parse(localStorage.getItem("todo")) || [];
todoDisplay();
}
function handleKeyDown(event) {
if (event.key === "Enter") {
addTodo();
}
}
function addTodo() {
let todo = todoInput.value.trim();
if (todo === "") return;
todos.push({text: todo, done: false});
todoInput.value = "";
localStorage.setItem("todo", JSON.stringify(todos));
todoDisplay();
}
function todoDisplay() {
if (todos.length === 0) {
todoList.innerHTML = `<p>할 일이 없습니다. 할 일을 추가해보세요.</p>`;
return;
}
let html = "";
for (let i = 0; i < todos.length; i++) {
html += `
<div id="todo-item-${i}" class="${todos[i].done ? "done" : ""}">
<input type="checkbox" ${todos[i].done ? "checked" : ""} onclick="toggleDone(${i})">
<span id="todo-text-${i}" onclick="editTodo(${i})">${escapeHtml(todos[i].text)}</span>
<button class="deleteBtn" onclick="deleteTodo(${i})">X</button>
</div>
`;
}
todoList.innerHTML = html;
}
function toggleDone(n) {
todos[n].done = !todos[n].done;
localStorage.setItem("todo", JSON.stringify(todos));
todoDisplay();
}
function editTodo(n) {
const span = document.querySelector(`#todo-text-${n}`);
span.outerHTML = `
<input id="todo-text-${n}" type="text" value="${escapeHtml(todos[n].text)}" onblur="saveTodo(${n}, this.value)" onkeydown="if(event.key==='Enter') this.blur()">
`;
}
function saveTodo(n, val) {
if (val.trim() === "") {
todoDisplay();
return;
}
todos[n].text = val;
localStorage.setItem("todo", JSON.stringify(todos));
todoDisplay();
}
function deleteTodo(n) {
todos.splice(n, 1);
localStorage.setItem("todo", JSON.stringify(todos));
todoDisplay();
}
todoInit();