JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text">
<button onclick="add()">新增</button>
<div id="root">
</div>
CSS
* {
margin: 0;
padding: 0;
list-style: none;
}
span {
margin-right: 10px;
}
JavaScript
var todos = [
{
title: "倒垃圾"
},
{
title: "繳電話費"
},
{
title: "採買本週食材"
},
];
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 = '刪除';
li.append(span);
li.append(deleteBtn);
ul.append(li);
deleteBtn.onclick = () => {
todos.splice(index, 1);
render();
}
}
}
function add() {
const input = document.querySelector('input');
if (input.value.trim() === "") return;
const newTodo = { title: input.value };
todos.push(newTodo);
render();
input.value = "";
}
render();