بتل کد Battle Codeدارد باز می‌شود…

Which Button? چالش 4 از جلسه‌ی 32، متوسط

سه دکمه داخل جعبه‌ی #colors هستند و فقط یک تابع به کلیک روی جعبه گوش می‌دهد. پیام باید بشود You chose Red (یا Green یا Blue).
برنامه خط قرمز دارد، چون event.target ممکن است هر چیزی باشد.
event.target را با instanceof HTMLButtonElement باریک کن. اگر کلیک روی جای خالیِ جعبه بود، پیام نباید عوض شود.

<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) => {
    msg.textContent = "You chose " + event.target.textContent;
  });
}
</script>

راهنما و جواب این چالش · برگشت به درس جلسه‌ی 32: رویدادها با نوع · چالش بعدی: Find the Red Lines

بیشتر بخوان: جاوااسکریپت چیست؟ از دکمه‌ی وب تا Node.js