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>
<button onclick="exportTodos()">匯出</button>
<button onclick="saveTodos()">儲存</button>
CSS
* {
margin: 0;
padding: 0;
list-style: none;
}
li {
margin: 10px 0;
}
span {
margin-right: 10px;
}
button {
cursor: pointer;
}
button + button {
margin-left: 10px;
}
JavaScript
let todos = [
{
title: "倒垃圾",
category: "normal",
isCompleted: false
},
{
title: "繳電話費",
category: "important",
isCompleted: false
},
{
title: "採買本週食材",
category: "urgent",
isCompleted: false
},
];
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 todoText = document.createElement('span');
const deleteBtn = document.createElement('button');
const isCompleteBtn = document.createElement('button');
const finish = document.createElement('span');
todoText.textContent = todos[index].title;
finish.textContent = '(已完成)';
deleteBtn.textContent = '刪除';
if (todos[index].category === 'important') {
todoText.style.color = 'orange';
} else if (todos[index].category === 'urgent') {
todoText.style.color = 'red';
}
if (todos[index].isCompleted) {
isCompleteBtn.textContent = '標示為未完成';
finish.style.display = 'inline';
} else {
isCompleteBtn.textContent = '標示為已完成';
finish.style.display = 'none'
}
li.append(todoText);
li.append(finish);
li.append(isCompleteBtn);
li.append(deleteBtn);
ul.append(li);
deleteBtn.onclick = () => {
todos.splice(index, 1);
render();
}
isCompleteBtn.onclick = () => {
todos[index].isCompleted = !todos[index].isCompleted;
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,
isCompleted: false,
};
todos.push(newTodo);
render();
input.value = "";
}
function exportTodos() {
let result = '';
let num = 1;
for (let todo of todos) {
if (todo.category ===...