JSFiddle - React, Tailwind, and code Playground
HTML
<h1 style="text-align: center;">JavaScript 系列六:第3課 ── 認識匿名函式</h1>
<div class="control">
<input type="text">
<button onclick="add()">新增</button>
</div>
<div id="root">
</div>
CSS
* {
padding: 0;
margin: 0;
/* 因為作業一要求的結構沒有::marker,所以用CSS除掉。::marker是ul裡面的li的前綴黑點 */
list-style-type: none;
}
.control {
margin-top: 20px;
display: flex;
justify-content: center;
}
ul {
display: flex;
flex-direction: column;
align-items: center;
}
li {
margin: 20px;
}
JavaScript
var todos = [{
title: "倒垃圾"
},
{
title: "繳電話費"
},
{
title: "採買本週食材"
}
];
function render() {
// 請寫出此函式內容
let root = document.querySelector("#root");
root.textContent = "";
let ul = document.createElement("ul");
for (const index in todos) {
let titleBox = document.createElement("li");
let title = document.createElement("span");
title.textContent = todos[index].title;
titleBox.append(title);
let deleteBtn = document.createElement("button");
deleteBtn.textContent = "刪除";
titleBox.append(deleteBtn);
deleteBtn.onclick = () => {
// 請寫出此 arrow function 內容(更新 todos 陣列)
todos.splice(index, 1);
render();
};
ul.append(titleBox);
}
root.append(ul);
}
function add() {
// 請寫出此函式內容(更新 todos 陣列)
let input = document.querySelector("input");
if (input.value === "") {
alert("請輸入文字");
return;
}
let newAdd = {
title: input.value
};
todos.push(newAdd);
input.value = "";
render();
}
render();