如何编写无冗余代码的多功能JavaScript分步内容显示函数
优化方案
你可以把组ID作为参数抽离,用一个对象存储不同分组的当前步数,就能实现一套代码适配任意多组需求了,改动很小且和你现有逻辑完全兼容:
第一步:替换原有冗余JS代码
把之前写的多套Function1、Function2全删掉,替换成下面这段通用代码:
// 存储每个步骤组的当前进度,key为组ID,value为当前展示到第几步 const stepProgress = {}; // 通用展示下一个步骤的函数,参数为组编号(比如1、2、3...) function showStep(groupId) { // 初始化该组的进度为1 if (!stepProgress[groupId]) stepProgress[groupId] = 1; const currentStep = stepProgress[groupId]; const stepEl = document.getElementById(`Step${groupId}-${currentStep}`); if (!stepEl) return; // 显示当前步骤 stepEl.style.visibility = 'visible'; // 进度+1 stepProgress[groupId]++; // 判断是否还有下一个步骤,没有就禁用step按钮 if (!document.getElementById(`Step${groupId}-${stepProgress[groupId]}`)) { document.getElementById(`step${groupId}`).disabled = true; } // 启用重置按钮 document.getElementById(`reset${groupId}`).disabled = false; } // 通用重置步骤的函数,参数为组编号 function resetSteps(groupId) { // 重置进度为1 stepProgress[groupId] = 1; // 启用step按钮,禁用重置按钮 document.getElementById(`step${groupId}`).disabled = false; document.getElementById(`reset${groupId}`).disabled = true; // 遍历隐藏该组所有步骤 let i = 1; let stepEl; while (stepEl = document.getElementById(`Step${groupId}-${i}`)) { stepEl.style.visibility = 'hidden'; i++; } }
第二步:优化CSS选择器
不用挨个写步骤ID,直接用属性选择器匹配所有步骤元素,新增多少组都不用改CSS:
[id^="Step"] { visibility: hidden; }
[id^="Step"]代表匹配所有ID以Step开头的元素,完全适配你当前的命名规则。
第三步:修改HTML按钮的调用方式
按钮的onclick事件直接传组编号即可,比如第一组传1,第二组传2:
<!-- 第一组按钮 --> <input type="button" onclick="showStep(1)" value="Steps" id="step1"/> <input type="button" onclick="resetSteps(1)" value="Reset" id="reset1" disabled="true"/> <!-- 第二组按钮 --> <input type="button" onclick="showStep(2)" value="Steps" id="step2"/> <input type="button" onclick="resetSteps(2)" value="Reset" id="reset2" disabled="true"/>
后续新增第N组的时候,只需要按照规则命名步骤ID为StepN-1/2/3...,按钮ID为stepN、resetN,调用函数时传N即可,不需要再新增JS代码。
内容的提问来源于stack exchange,提问作者welh
相关产品推荐
相关产品推荐

