جواب «Which Button?» چالش 4 از جلسهی 32
سؤال
سه دکمه داخل جعبهی #colors هستند و فقط یک تابع به کلیک روی جعبه گوش میدهد. پیام باید بشود You chose Red (یا Green یا Blue).
برنامه خط قرمز دارد، چون event.target ممکن است هر چیزی باشد.event.target را با instanceof HTMLButtonElement باریک کن. اگر کلیک روی جای خالیِ جعبه بود، پیام نباید عوض شود.
راهنما
اول const target = event.target; بعد if (target instanceof HTMLButtonElement) { msg.textContent = "You chose " + target.textContent; }
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
#colors { padding: 16px; border-radius: 12px; background: #e2e8f0; }
</style>
<div id="colors">
<button id="red">Red</button>
<button id="green">Green</button>
<button id="blue">Blue</button>
</div>
<p id="msg"></p>
<script type="text/typescript">
const colors = document.getElementById("colors");
const msg = document.getElementById("msg");
if (colors && msg) {
colors.addEventListener("click", (event) => {
const target = event.target;
if (target instanceof HTMLButtonElement) {
msg.textContent = "You chose " + target.textContent;
}
});
}
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن