جواب «Add Here, See There» چالش 7 از جلسهی 14
سؤال
دفتر لغت دو صفحه دارد: #add برای نوشتن کلمه و #list برای دیدن کلمهها. show آماده است. render() را بنویس که آرایهی words را در #words به شکل li بکشد و در #count بنویسد Words: 2. addWord(event) را هم بنویس: جلوی ثبت فرم را بگیرد، متن خالی را (با trim) رد کند، کلمه را push کند، کادر #word را خالی کند، render() کند و با show("list") به صفحهی لیست برود.
راهنما
در render اول list.innerHTML = ""، بعد برای هر کلمه createElement("li") و textContent. در addWord خط اول event.preventDefault(); است و آخرین خط show("list");.
یک جواب درست
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Word Book</title>
<style>
body { font-family: sans-serif; margin: 0; background-color: #f6f7fb; }
header { background-color: #3949ab; color: white; padding: 12px 16px; }
.screen { max-width: 420px; margin: 0 auto; padding: 16px 16px 90px; }
.screen { display: none; }
nav { position: fixed; bottom: 0; left: 0; right: 0; display: flex; background-color: white; }
nav button { flex: 1; min-height: 56px; font-size: 16px; border: none; background-color: white; }
nav button.active { background-color: #ffd23f; font-weight: bold; }
input { font-size: 16px; min-height: 44px; }
form button { min-height: 44px; font-size: 16px; }
</style>
</head>
<body>
<header><h1>Word Book</h1></header>
<section class="screen" id="add">
<h2>New word</h2>
<form id="addForm" onsubmit="addWord(event)">
<label for="word">Word</label>
<input id="word" placeholder="apple">
<button>Add</button>
</form>
</section>
<section class="screen" id="list">
<h2>My words</h2>
<p id="count">Words: 0</p>
<ul id="words"></ul>
</section>
<nav>
<button id="tab-add" onclick="show('add')">Add</button>
<button id="tab-list" onclick="show('list')">Words</button>
</nav>
<script>
let words = [];
function show(name) {
let screens = document.querySelectorAll(".screen");
for (let screen of screens) {
screen.style.display = "none";
}
document.getElementById(name).style.display = "block";
let tabs = document.querySelectorAll("nav button");
for (let tab of tabs) {
tab.classList.remove("active");
}
document.getElementById("tab-" + name).classList.add("active");
}
function render() {
let list = document.getElementById("words");
list.innerHTML = "";
for (let word of words) {
let li = document.createElement("li");
li.textContent = word;
list.appendChild(li);
}
document.getElementById("count").textContent = "Words: " + words.length;
}
function addWord(event) {
event.preventDefault();
let box = document.getElementById("word");
let word = box.value.trim();
if (word === "") {
return;
}
words.push(word);
box.value = "";
render();
show("list");
}
show("add");
</script>
</body>
</html>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن