JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text">
<select name="category" id="category">
<option value="normal">一般</option>
<option value="important">重要</option>
<option value="urgent">緊急</option>
</select>
<button onclick="add()">新增事項</button>
<div id="root">
CSS
ul{
list-style: none;
}
JavaScript
const root=document.querySelector("#root");
let todos = [
{
title: "倒垃圾",
category: "normal"
},
{
title: "繳電話費",
category: "important"
},
{
title: "採買本週食材",
category: "urgent"
},
];
function render(){
root.innerHTML="";
for(let index in todos){
let ul=document.createElement("ul");
let li=document.createElement("li");
let span=document.createElement("span");
let deleteBtn=document.createElement("button");
root.append(ul);
ul.append(li);
li.append(span)
li.append(deleteBtn);
span.textContent=todos[index].title;
deleteBtn.textContent="刪除";
if(todos[index].category=="important"){
span.style.color="#FF8000";
}else if(todos[index].category=="urgent"){
span.style.color="#F00";
}
deleteBtn.onclick=()=>{
console.log(index);
console.log(todos);
todos.splice(index, 1);
render();
}
}
}
function add(){
let event=document.querySelector("[type=text]");
let color=document.querySelector("#category");
todos.push({title: event.value, category: color.value});
render();
event.value="";
}
render();