JSFiddle - React, Tailwind, and code Playground
HTML
<h1 style="text-align: center;">JavaScript 系列六:第7課 ── 資料序列化</h1>
<div class="control">
<input type="text" placeholder="請輸入事項" required>
<select required>
<option value="" disabled selected>請選擇程度分類</option>
<option value="normal">一般</option>
<option value="important">重要</option>
<option value="urgent">緊急</option>
</select>
<button onclick="add()">新增</button>
</div>
<div id="root">
</div>
<!-- 因export是JS reserved word,故稍加修改名稱 -->
<button id="store" onclick="store()">儲存</button>
<button id="export" onclick="exportList()">匯出</button>
CSS
* {
padding: 0;
margin: 0;
/* 因為作業一要求的結構沒有::marker,所以用CSS除掉。::marker是ul裡面的li的前綴黑點 */
list-style-type: none;
}
body {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.control {
margin-top: 20px;
display: flex;
justify-content: center;
}
ul {
display: flex;
flex-direction: column;
align-items: center;
}
li {
margin: 20px;
}
#store,
#export {
width: 50px;
}
JavaScript
var todos = [{
title: "倒垃圾",
category: "normal",
isCompleted: false
},
{
title: "繳電話費",
category: "important",
isCompleted: false
},
{
title: "採買本週食材",
category: "urgent",
isCompleted: false
}
];
function render() {
// 請寫出此函式內容
let root = document.querySelector("#root");
root.textContent = "";
let ul = document.createElement("ul");
for (const index in todos) {
let todo = todos[index];
let list = document.createElement("li");
let title = document.createElement("span");
title.textContent = todo.title;
if (todo.category === "normal") {
title.style.color = "#000";
} else if (todo.category === "important") {
title.style.color = "#fa0";
} else {
title.style.color = "#f00";
}
list.append(title);
let toggleBtn = document.createElement("button");
let status = document.createElement("span");
if (todo.isCompleted) {
toggleBtn.textContent = "標示未完成";
status.textContent = "(已完成)";
} else {
toggleBtn.textContent = "標示已完成";
status.textContent = "";
}
toggleBtn.onclick = () => {
// 請寫出此 arrow function 內容(更新 todos 陣列)
if (!todo.isCompleted) {
todo.isCompleted = true;
} else {
todo.isCompleted = false;
}
render();
};
list.append(status);
list.append(toggleBtn);
let deleteBtn = document.createElement("button");
deleteBtn.textContent = "刪除";
list.append(deleteBtn);
deleteBtn.onclick = () => {
// 請寫出此 arrow function 內容(更新 todos 陣列)
todos.splice(index, 1);
render();
};
ul.append(list);
}
root.append(ul);
}
function add() {
// 請寫出此函式內容(更新 todos 陣列)
let input = document.querySelector("input");
let select = document.querySelector("select");
if (input.value === "" || select.value === "") {
alert("請輸入文字與程度分類");
return;
}
let newAdd = {
title: input.value,
category: select.value,
...