迷你高尔夫在线计分卡优化:实现1-4玩家通用函数避免重复代码
优化迷你高尔夫计分卡代码(支持1-4名玩家)
通过通用化函数+统一命名规则可以彻底消除重复代码,同时轻松扩展到1-4名玩家。核心思路是让计分函数接受玩家编号作为参数,根据编号动态获取对应数据并计算总和。
修改后的HTML代码
<table> <thead> <tr> <th>Trou</th> <th>Par</th> <!-- 动态生成1-4名玩家的表头 --> <?php for ($player = 1; $player <= 4; $player++) : ?> <th><input type="text" value="#<?= $player ?>"></th> <?php endfor; ?> </tr> </thead> <tbody> <?php for ($i = 1; $i < 19; $i++) : ?> <tr> <td><?= $i ?></td> <td>2</td> <!-- 为每个玩家生成对应洞的分数输入框 --> <?php for ($player = 1; $player <= 4; $player++) : ?> <td> <input onblur="calculateTotal(<?= $player ?>)" type="number" name="qty-<?= $player ?>" id="qty-<?= $player ?>-<?= $i ?>" min="0" /> </td> <?php endfor; ?> </tr> <?php endfor; ?> <tr> <td>Total</td> <td>52</td> <!-- 生成每个玩家的总分显示框 --> <?php for ($player = 1; $player <= 4; $player++) : ?> <td><input type="text" name="total-<?= $player ?>" id="total-<?= $player ?>" readonly></td> <?php endfor; ?> </tr> </tbody> </table>
修改后的JavaScript代码
function calculateTotal(playerNum) { // 根据玩家编号获取该玩家所有洞的分数输入框 const scoreInputs = document.getElementsByName(`qty-${playerNum}`); let total = 0; for (const input of scoreInputs) { // 处理空输入或非数字,默认按0计算 const score = parseInt(input.value) || 0; total += score; } // 更新对应玩家的总分 document.getElementById(`total-${playerNum}`).value = total; }
关键优化点
- 统一命名规则:所有玩家的分数输入框命名为
qty-{玩家编号},总分框命名为total-{玩家编号},通过编号动态定位元素,避免硬编码 - 单一通用函数:
calculateTotal接受玩家编号参数,复用相同计算逻辑,无需为每个玩家编写重复函数 - 灵活扩展:调整PHP循环的上限(比如把
4改成3),就能快速切换支持的玩家数量 - 健壮性提升:用
parseInt(input.value) || 0处理空值或非数字输入,避免总分出现NaN
内容的提问来源于stack exchange,提问作者Yannick Benoit
相关产品推荐
相关产品推荐

