بتل کد Battle Codeدارد باز می‌شود…

جواب «Clear Done» چالش 5 از جلسه‌ی 7

سؤال

دکمه‌ی #clearDone تابع clearDone() را صدا می‌زند. آن را بنویس تا همه‌ی کارهای انجام‌شده را از todos بردارد و لیست را از نو بکشد.

راهنما

از آخر آرایه به اول برو (i--) و هر کار انجام‌شده را splice کن؛ اگر از اول بروی، بعد از هر حذف یک کار جا می‌ماند.

یک جواب درست

<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>
<ul id="list"></ul>
<button id="clearDone" onclick="clearDone()">Clear done</button>
<script>
let todos = [
  { text: "Feed the cat", done: false },
  { text: "Read a book", done: true },
  { text: "Tidy my desk", done: true },
  { text: "Water the plant", done: false },
  { text: "Practice piano", done: true },
];

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 toggle(i) {
  todos[i].done = !todos[i].done;
  render();
}

function removeAt(i) {
  todos.splice(i, 1);
  render();
}

function clearDone() {
  for (let i = todos.length - 1; i >= 0; i--) {
    if (todos[i].done) todos.splice(i, 1);
  }
  render();
}

render();
</script>

اول خودت امتحان کن؛ جواب‌های دیگر هم قبول است. برگرد و خودت حلش کن