You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS的IF ELSE语句内存在两处相似代码块,请问如何进行重构优化?

JS重复代码重构方案

针对你给出的if-else重复代码块,有以下几种常用的合理重构方案:

方案1:使用classList.toggle原生API(最简洁)

classList.toggle方法支持第二个布尔类型的参数,参数为true时添加指定类名,为false时移除指定类名,正好匹配你的需求,同时提前缓存DOM查询结果避免重复查询DOM:

const addNotesBtn = document.querySelector(`.card-${domain.id} .add-notes-button`);
addNotesBtn.classList.toggle('notes-filled', !!notesValue);

注:该API在所有现代浏览器中都兼容,无需兼容IE环境可直接使用。

方案2:缓存DOM节点后保留分支逻辑

如果后续需要在if/else分支中补充其他业务逻辑,可以只优化重复的DOM查询部分,保留原有分支结构:

const addNotesBtn = document.querySelector(`.card-${domain.id} .add-notes-button`);
if (notesValue) {
  addNotesBtn.classList.add('notes-filled');
  // 可补充其他添加类名后的逻辑
} else {
  addNotesBtn.classList.remove('notes-filled');
  // 可补充其他移除类名后的逻辑
}

方案3:封装为通用工具函数

如果项目中存在大量类似的类名切换需求,可以把逻辑封装成可复用的工具函数,减少全项目的重复代码:

/**
 * 切换元素的指定类名
 * @param {string} selector 元素选择器
 * @param {string} className 要切换的类名
 * @param {boolean} condition 切换条件:true加类,false删类
 */
function toggleElementClass(selector, className, condition) {
  const targetEl = document.querySelector(selector);
  // 加可选链避免元素不存在时报错
  targetEl?.classList.toggle(className, !!condition);
}

// 业务代码中直接调用即可
toggleElementClass(`.card-${domain.id} .add-notes-button`, 'notes-filled', notesValue);

内容的提问来源于stack exchange,提问作者ysmdesigninc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 19:36:03