جواب «Read the Field» چالش 3 از جلسهی 31
سؤال
این برنامه در جاوااسکریپت کار میکرد: اسم را از کادر #name میخواند و در #msg مینویسد Hello, Sara!
در تایپاسکریپت سه خط قرمز دارد. درستش کن:
- کادر را با نوع HTMLInputElement بگیر (با querySelector<HTMLInputElement>("#name") یا با as).
- مطمئن شو که box و msg پیدا شدهاند.
متن پیام باید دقیقاً Hello, بهعلاوهی اسم و یک ! باشد.
راهنما
خط اول: const box = document.querySelector<HTMLInputElement>("#name"); و قبل از خط آخر: if (!box || !msg) { return; }
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
</style>
<input id="name" type="text" placeholder="Your name">
<button id="go" onclick="press()">Hello</button>
<p id="msg"></p>
<script type="text/typescript">
function press(): void {
const box = document.querySelector<HTMLInputElement>("#name");
const msg = document.getElementById("msg");
if (!box || !msg) {
return;
}
msg.textContent = "Hello, " + box.value + "!";
}
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن