Step 3: The Button چالش 3 از جلسهی 20، متوسط
قدم سوم: حالا صفحه یک دکمهی Next دارد که press() را صدا میزند.
- چهار خط show را پاک کن (هم Light: red و هم سه خط امتحانی).
- تابع draw(): void را بنویس که Light: و رنگ الان را با show مینویسد.
- تابع press(): void را بنویس: light را به next(light) عوض میکند و بعد draw() را صدا میزند.
- در آخر برنامه یک بار draw() را صدا بزن.
اول باید فقط Light: red دیده شود. با هر بار زدن دکمه یک خط تازه میآید: Light: green، Light: yellow، Light: red.
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#out { direction: ltr; text-align: left; font: 16px monospace; margin: 12px 0; padding: 12px; min-height: 28px; border-radius: 12px; background: #0f172a; color: #e2e8f0; white-space: pre-wrap; overflow-wrap: anywhere; }
#out .line { min-height: 22px; }
</style>
<button id="go" onclick="press()">Next</button>
<pre id="out"></pre>
<script type="text/typescript">
// 1. the type Light and the box light
type Light = "red" | "green" | "yellow";
let light: Light = "red";
show("Light: " + light);
// 2. the function next
function next(now: Light): Light {
switch (now) {
case "red":
return "green";
case "green":
return "yellow";
case "yellow":
return "red";
default: {
const forgot: never = now;
return forgot;
}
}
}
show(next("red"));
show(next("green"));
show(next("yellow"));
// 3. the button
</script>
راهنما و جواب این چالش · برگشت به درس جلسهی 20: پروژه: چراغ راهنماییای که اشتباه نمیکند · چالش بعدی: Step 4: Stop, Go, Wait
بیشتر بخوان: جاوااسکریپت چیست؟ از دکمهی وب تا Node.js