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

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

سؤال

زیر لیست، #count باید بگوید چند کار انجام شده، مثل 3 of 5 done. render() را عوض کن تا کارهای انجام‌شده را بشمارد و این جمله را در #count بنویسد. بعد از هر تیک و حذف باید درست بماند.

راهنما

قبل از for: let done = 0; داخلش: if (todos[i].done) done++; بعد از آن: done + " of " + todos.length + " done".

یک جواب درست

<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>
<p id="count"></p>
<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 = "";
  let done = 0;
  for (let i = 0; i < todos.length; i++) {
    if (todos[i].done) done++;
    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);
  }
  document.getElementById("count").textContent = done + " of " + todos.length + " done";
}

function toggle(i) {
  todos[i].done = !todos[i].done;
  render();
}

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

render();
</script>

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