如何移除下述方法中的代码重复并优化jQuery代码可读性
代码优化方案
完全可以将重复逻辑合并,优化后代码可读性、可维护性都会大幅提升,同时还能修复原代码重复绑定点击事件的隐患,具体实现如下:
第一步:合并三个arrange系列函数为通用方法
提取不同尺寸的差异点为配置参数,所有逻辑统一维护:
function arrangeColors(size) { // 不同尺寸对应配置,后续新增尺寸只需要加一行配置即可 const sizeConfig = { 3: { maxLoop: 12, modLimit: 3 }, 4: { maxLoop: 18, modLimit: 4 }, 5: { maxLoop: 24, modLimit: 5 } // modLimit=5时i%5<5恒成立,等价于5x5的全量处理逻辑 }; const { maxLoop, modLimit } = sizeConfig[size]; for (let i = 0; i <= maxLoop; i++) { if (i % 5 < modLimit) { const randomColor = getValidColor(); manipulateButtons(i, randomColor); seenColors.push(randomColor); } } const nextColor = getRandomColor(seenColors); $("#next").attr("class", "btn next " + nextColor); return nextColor; }
第二步:合并三个难度按钮的点击事件
不需要修改HTML结构,直接匹配ID规则绑定统一逻辑,同时增加解绑逻辑避免重复绑定点击事件:
// 统一匹配所有以ToThree结尾的难度按钮 $('[id$="ToThree"]').click(function() { // 从按钮ID中提取对应尺寸 const sizeMap = { 'three': 3, 'four': 4, 'five': 5 }; const size = sizeMap[this.id.split('To')[0]]; playSound("Start"); executeTimer(); let nextColor = arrangeColors(size); // 先解绑之前绑定的事件,避免多次点击难度按钮后重复触发 $("#grid .btn").off('click').click(function() { animatePress(this); if ($(this).attr("id") === nextColor) { playSound("Success"); totalPoint += 10; console.log("Total Point: " + totalPoint); seenColors = []; nextColor = arrangeColors(size); } else { playSound("Failure"); } }); });
优化收益
- 冗余代码减少70%,所有规则逻辑只需要修改一次即可全量生效
- 新增其他尺寸难度时,只需要在配置项中增加对应参数,不需要重写整套逻辑
- 修复了原代码多次点击难度按钮会重复绑定网格点击事件、导致多次触发逻辑的bug
内容的提问来源于stack exchange,提问作者Semih Ataman
相关产品推荐
相关产品推荐

