Javascript todolist 經典題實作
資料初始化渲染
創建一個todolist.html
<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> <script src="index.js"></script> </body> </html>
|
創建index.js
let data = [ { content: "起床", }, { content: "吃早餐", }, ]; function initData() { let str = ""; data.forEach(function (item) { str += `<li>${item.content}<input class="delete" type="button" value="刪除待辦"></li>`; }); document.querySelector(".todo-list").innerHTML = str; } initData();
|
效果:
新增待辦事項
index.js
更新如下
const txt = document.querySelector(".txt"); const create = document.querySelector(".create"); let data = []; function initData() { let str = ""; data.forEach(function (item) { str += `<li>${item.content}<input class="delete" type="button" value="刪除待辦"></li>`; });
document.querySelector(".todo-list").innerHTML = str; }
create.addEventListener("click", function (e) { if (txt.value === "") { alert("請輸入待辦事項"); return; } data.push({ content: txt.value }); initData(); });
|
效果:
刪除待辦事項
index.js
更新如下
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) { 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(); } });
|
codepen
See the Pen
JavaScript 必修篇 - todolist 待辦事項 by 王冠智 (@joe94113)
on CodePen.
這邊順便推薦一個 css 選擇器的小遊戲
Javascript todolist 經典題實作