javascript_series6_render_function_advanced
by aelgy369
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>
JavaScript
var todos = [
{
title: "倒垃圾",
category: "normal"
},
{
title: "繳電話費",
category: "important"
},
{
title: "採買本週食材",
category: "urgent"
},
];
function render() {
const root = document.querySelector('#root')
const ul = document.createElement('ul');
// 之前忘了加 root.textContent,所以按下刪除鍵後會重複跑內容
root.textContent = '';
root.append(ul)
for (let index in todos) {
const li = document.createElement('li');
const span = document.createElement('span');
const deleteBtn = document.createElement('button');
span.innerText = todos[index].title;
li.append(span, deleteBtn);
ul.append(li);
deleteBtn.innerText = '刪除'
deleteBtn.onclick = () => {
todos.splice(index, 1)
render();
}
if (todos[index].category == 'important') {
span.style.color = 'orange';
} else if (todos[index].category == 'urgent') {
span.style.color = 'red';
}
}
}
function add()
{
const input = document.querySelector('input');
if (input.value.length > 0) {
alert('請輸入正確文字')
}
const select = document.querySelector('select')
let item = {
title: input.value,
category: select.value
}
todos.push(item)
render();
input.value = '';
}
render()