جواب «Clear Everything» چالش 6 از جلسهی 8
سؤال
کاربر باید بتواند دادهاش را پاک کند. دکمهی #clear تابع clearAll() را صدا میزند. آن را بنویس: لیست را خالی کن (todos = [])، آن را ذخیره کن و از نو بکش. اگر خواستی، اول با confirm بپرس.
راهنما
todos = []; بعد salam.save("todos", todos); و render();
یک جواب درست
<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>
<button id="clear" onclick="clearAll()">Clear everything</button>
<script>
let todos = salam.load("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 = "";
salam.save("todos", todos);
render();
}
function toggle(i) {
todos[i].done = !todos[i].done;
salam.save("todos", todos);
render();
}
function removeAt(i) {
todos.splice(i, 1);
salam.save("todos", todos);
render();
}
function clearAll() {
if (!confirm("Clear the whole list?")) return;
todos = [];
salam.save("todos", todos);
render();
}
render();
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن