جواب «Find the Bugs» چالش 6 از جلسهی 27
سؤال
این برنامه باید بعد از هر دکمه بنویسد چند اتاق روشن است، مثل On: 2. ولی عددِ درست را نشان نمیدهد.
دو اشتباه دارد. هر دو را پیدا و درست کن. (راهنمایی: return کجا نوشته شده؟ و countOn چطور صدا زده شده؟)
راهنما
return داخل حلقه است، پس تابع بعد از اولین اتاق تمام میشود؛ آن را بعد از آکولادِ بستهی حلقه ببر. و countOn پرانتز میخواهد: countOn().
یک جواب درست
<style>
body { font-family: sans-serif; text-align: center; padding: 16px; }
button, input, select { font-size: 16px; min-height: 40px; margin: 4px; }
.house { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px; max-width: 340px; margin: 12px auto; }
.room { width: 150px; padding: 18px 0; border-radius: 12px; background: #334155; color: white; }
.room.on { background: #fde047; color: black; }
</style>
<div class="house">
<div id="kitchen" class="room">Kitchen</div>
<div id="bedroom" class="room">Bedroom</div>
<div id="living" class="room">Living room</div>
<div id="bath" class="room">Bath</div>
</div>
<button id="b-kitchen" onclick="flip('kitchen')">Kitchen</button>
<button id="b-bedroom" onclick="flip('bedroom')">Bedroom</button>
<button id="b-living" onclick="flip('living')">Living room</button>
<button id="b-bath" onclick="flip('bath')">Bath</button>
<p id="msg"></p>
<script>
let rooms = document.querySelectorAll(".room");
function countOn() {
let count = 0;
for (const room of rooms) {
if (room.classList.contains("on")) {
count++;
}
}
return count;
}
function show() {
document.getElementById("msg").textContent = `On: ${countOn()}`;
}
function flip(id) {
document.getElementById(id).classList.toggle("on");
show();
}
</script>
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن