如何将18组重复的JavaScript按钮点击函数合并为单个函数?
精简18个座位按钮的重复JS代码方案
核心优化思路
- 给所有座位容器(td标签)添加统一类名,实现批量选择
- 把切换样式、填充输入框的逻辑合并成单个函数,消除冗余
- 批量绑定点击事件,不用为每个座位写重复代码
修改后的HTML
给所有带seatButtonX id的td标签加上统一类seat-button-container,示例如下:
<article class="column1"> <table class="table_seats"> <tr> <td id="seatButton1" class="seat-button-container seatLargeGreen" colspan="2"> <button class="seat_button_large">1</button> </td> <td class="aisle" rowspan="3"></td> <td id="seatButton2" class="seat-button-container seatLargeGreen" colspan="2"> <button class="seat_button_large">2</button> </td> </tr> <!-- 剩余16个座位的td标签同样添加seat-button-container类 --> </table> </article> <!-- 对应输入框 --> <input type="text" id="snum"> <input type="text" id="sclass">
精简后的JavaScript代码
// 统一处理座位点击的函数 function handleSeatClick(seatElement) { // 切换样式类 const hasGreenClass = seatElement.classList.contains('seatLargeGreen'); const hasBlueClass = seatElement.classList.contains('seatLargeBlue'); if (hasGreenClass) { seatElement.classList.replace('seatLargeGreen', 'seatLargeBlue'); } else if (hasBlueClass) { seatElement.classList.replace('seatLargeBlue', 'seatLargeGreen'); } // 更新输入框内容 const seatNum = seatElement.querySelector('.seat_button_large').textContent.trim(); const snumInput = document.getElementById('snum'); const sclassInput = document.getElementById('sclass'); if (seatElement.classList.contains('seatLargeBlue')) { snumInput.value = seatNum; sclassInput.value = "Business"; } else { snumInput.value = ""; sclassInput.value = ""; } } // 页面加载完成后批量绑定事件 document.addEventListener('DOMContentLoaded', function() { const allSeats = document.querySelectorAll('.seat-button-container'); allSeats.forEach(seat => { seat.addEventListener('click', function() { handleSeatClick(this); }); }); });
关键优化点
- 用
classList替代直接操作className,避免意外覆盖其他类名 - 从按钮文本中自动获取座位号,不用硬编码数字,新增座位时无需修改JS
- 合并原本拆分的两个点击逻辑,减少重复代码量
- 批量选择元素绑定事件,一次性处理所有18个座位
内容的提问来源于stack exchange,提问作者user20386738
相关产品推荐
相关产品推荐

