todo lists
by superyngo
HTML
<input type="text">
<button onclick="add()">新增</button>
<hr>
<div id="root">
</div>
CSS
*,
*::before,
*::after {
box-sizing: border-box;
}
img,
picture,
svg,
video {
display: block;
}
* {
margin: 0;
padding: 0;
font: inherited;
}
html {
color-scheme: dark light;
}
body {
min-height: 100svh;
}
li {
list-style: none;
}
JavaScript
var todos = [
{
title: "倒垃圾",
},
{
title: "繳電話費",
},
{
title: "採買本週食材",
},
];
function render() {
console.log(todos);
const root = document.querySelector("#root");
root.textContent = "";
const ul = document.createElement("ul");
root.append(ul);
todos.forEach((todo, index) => {
const li = document.createElement("li");
const delBtn = document.createElement("button");
li.textContent = todo.title;
delBtn.textContent = "刪除";
delBtn.onclick = () => {
todos.splice(index, 1);
render();
};
ul.append(li, delBtn);
});
}
function add() {
const toAdd = document.querySelector("input");
todos.push({ title: toAdd.value });
console.log(toAdd);
render();
}
render();