Step 4: Save and Load چالش 4 از جلسهی 9، متوسط
قدم ۴ از ۴: اپ باید یادش بماند. todos را با salam.load("todos", []) بخوان (دو کار نمونه دیگر لازم نیست؛ بار اول لیست خالی است) و در add، toggle و removeAt بعد از هر تغییر salam.save("todos", todos) را صدا بزن.
<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; background-color: #f4f7fb; }
h1 { color: #2a5bd7; }
form { display: flex; column-gap: 8px; }
input { font-size: 16px; min-height: 44px; }
#t { flex: 1; padding: 0 8px; }
input[type="checkbox"] { min-height: 0; width: 24px; height: 24px; }
button { font-size: 16px; min-height: 44px; }
li { padding: 8px 0; font-size: 18px; }
.done { text-decoration: line-through; color: gray; }
</style>
<h1>My Day</h1>
<form id="addForm" onsubmit="add(event)">
<input id="t" placeholder="New task">
<button>Add</button>
</form>
<ul id="list"></ul>
<p id="count"></p>
<script>
let todos = [
{ text: "Brush teeth", done: false },
{ text: "Pack school bag", done: false },
];
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 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>
راهنما و جواب این چالش · برگشت به درس جلسهی 9: پروژه: کارهای روزانه
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js