جواب «Add from the Box» چالش 3 از جلسهی 32
سؤال
render آماده است. تابع addItem را بنویس:
- اگر کادر خالی است (box.value === "")، هیچ کاری نکن.
- وگرنه متن کادر را به آرایهی items اضافه کن، کادر را خالی کن و render() را صدا بزن.
خودت li نساز؛ این کارِ render است.
راهنما
if (box.value !== "") { items.push(box.value); box.value = ""; render(); }
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
ul { list-style: none; padding: 0; max-width: 260px; margin: 12px auto; }
li { padding: 8px; margin: 4px 0; border-radius: 8px; background: #e2e8f0; overflow-wrap: anywhere; }
li.done { background: #86efac; text-decoration: line-through; }
</style>
<input id="item" aria-label="Item" placeholder="Milk">
<button id="add" onclick="addItem()">Add</button>
<ul id="list"></ul>
<script>
let items = [];
let list = document.getElementById("list");
let box = document.getElementById("item");
function render() {
list.textContent = "";
for (let item of items) {
let li = document.createElement("li");
li.textContent = item;
list.append(li);
}
}
function addItem() {
if (box.value !== "") {
items.push(box.value);
box.value = "";
render();
}
}
render();
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن