<html>
<head>
<title>Js todolist</title>
</head>
<body>
<input type="text" placeholder="輸入待辦事項" class="txt" />
<input type="button" class="create" value="新增待辦" />
<ul class="todo-list"></ul>
</body>
</html>
const txt = document.querySelector(".txt");
const create = document.querySelector(".create");
const list = document.querySelector(".todo-list");
let data = [];
function initData() {
let str = "";
data.forEach(function (item, index) {
// 利用取得index知道該刪除哪一個li tag
str += `<li>${item.content}<input class="delete" type="button" data-num=${index} value="刪除待辦"></li>`;
});
document.querySelector(".todo-list").innerHTML = str;
}
// 新增待辦監聽
create.addEventListener("click", function (e) {
if (txt.value === "") {
alert("請輸入待辦事項");
return;
}
data.push({ content: txt.value });
txt.value = ""; // 點擊輸入後,清空輸入框
initData();
});
// 刪除待辦監聽
list.addEventListener("click", function (e) {
if (e.target.className === "delete") {
data.splice(e.target.dataset.num, 1);
initData();
}
});
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.