جواب «Add, Then Tick» چالش 6 از جلسهی 7
سؤال
افزودن کار میکند، ولی هر کار فقط یک span دارد. render() را کامل کن تا داخل هر li به این ترتیب بسازد: یک input با type = "checkbox" که toggle(i) را صدا بزند، یک span با متن، و یک button با کلاس del و متن Delete که removeAt(i) را صدا بزند. به li کار انجامشده کلاس done بده.
راهنما
box.onchange = function () { toggle(i); }; و del.onclick = function () { removeAt(i); }; بعد li.append(box, span, del);
یک جواب درست
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { font-family: Tahoma, sans-serif; max-width: 420px; margin: 0 auto; padding: 12px; }
li { padding: 8px 0; font-size: 18px; }
form { display: flex; column-gap: 8px; }
input { font-size: 16px; min-height: 44px; }
input[type="checkbox"] { min-height: 0; width: 24px; height: 24px; }
button { font-size: 16px; min-height: 44px; }
.done { text-decoration: line-through; color: gray; }
</style>
<h1>My Tasks</h1>
<form id="addForm" onsubmit="add(event)">
<input id="t" placeholder="New task">
<button>Add</button>
</form>
<ul id="list"></ul>
<script>
let todos = [];
function render() {
let list = document.getElementById("list");
list.textContent = "";
for (let i = 0; i < todos.length; i++) {
let li = document.createElement("li");
let box = document.createElement("input");
box.type = "checkbox";
box.checked = todos[i].done;
box.onchange = function () { toggle(i); };
let span = document.createElement("span");
span.textContent = todos[i].text;
let del = document.createElement("button");
del.textContent = "Delete";
del.className = "del";
del.onclick = function () { removeAt(i); };
if (todos[i].done) li.classList.add("done");
li.append(box, span, del);
list.appendChild(li);
}
}
function add(event) {
event.preventDefault();
let box = document.getElementById("t");
let text = box.value.trim();
if (text === "") return;
todos.push({ text: text, done: false });
box.value = "";
render();
}
function toggle(i) {
todos[i].done = !todos[i].done;
render();
}
function removeAt(i) {
todos.splice(i, 1);
render();
}
render();
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن