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