-
Notifications
You must be signed in to change notification settings - Fork 1
/
todo.js
85 lines (75 loc) · 2.23 KB
/
todo.js
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
let button = document.getElementById("button");
let input = document.getElementById("input");
let list = document.getElementById("list");
let form = document.getElementById("form");
let toDos =
localStorage.todos === undefined ? [] : JSON.parse(localStorage.todos);
// cnt 초깃값 설정
if (!localStorage.getItem("cnt")) {
localStorage.setItem("cnt", 0);
}
// li 속성 구분할 값 num으로 지정
let num = localStorage.getItem("cnt");
function makeNum() {
// num 값을 cnt값에서 +1씩 추가해주기
if (num === undefined) {
num = 1;
} else {
num++;
localStorage.setItem("cnt", num);
}
return num;
}
function clickButton() {
let li = document.createElement("li");
let removeButton = document.createElement("button");
li.innerHTML = input.value;
removeButton.innerText = "삭제";
removeButton.addEventListener("click", removeOne);
li.appendChild(removeButton);
list.appendChild(li);
// li에 속성 부여하기
li.setAttribute("id", num);
let toDoObj = {
text: input.value,
id: num,
};
// toDos = JSON.parse(localStorage.getItem("todos"));
toDos.push(toDoObj);
// localStorage에 todos를 저장하기
localStorage.setItem("todos", JSON.stringify(toDos));
// 입력값 초기화
input.value = "";
num++;
}
function removeOne(event) {
let removing = event.target.parentElement;
removing.remove();
toDos = toDos.filter(function (lst) {
return lst.id !== parseInt(removing.id);
});
localStorage.setItem("todos", JSON.stringify(toDos));
}
function init() {
for (index in toDos) {
let stringList = toDos[index];
let valueText = stringList[Object.keys(stringList)[0]];
let valueId = stringList[Object.keys(stringList)[1]];
// todos 메모리에 저장된 값을 불러와서 list안에 다시 넣기
let dolist = document.createElement("li");
let dobtn = document.createElement("button");
dolist.setAttribute("id", valueId);
dolist.append(valueText);
dobtn.innerText = "삭제";
dobtn.addEventListener("click", removeOne);
dolist.appendChild(dobtn);
list.appendChild(dolist);
}
}
button.addEventListener("click", clickButton);
form.addEventListener("submit", (e) => {
e.preventDefault();
clickButton();
});
makeNum();
init();