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

如何优化JavaScript和jQuery编写的按钮点击代码?是否支持面向对象实现?

优化方案

原代码存在大量重复逻辑,后续新增/修改按钮时维护成本极高,以下提供两种优化方案:

基础简化版

核心思路是把按钮对应的执行函数、结束事件统一存在映射表中,用统一选择器批量绑定事件,不需要为每个按钮单独写重复的绑定逻辑:

// 统一配置所有按钮的关联逻辑
const btnMap = {
  1: {
    run: btn1Function,
    endEvent: btn1FunctionEndEvent
  },
  2: {
    run: btn2Function,
    endEvent: btn2FunctionEndEvent
  },
  3: {
    run: btn3Function,
    endEvent: btn3FunctionEndEvent
  },
  4: {
    run: btn4Function,
    endEvent: btn4FunctionEndEvent
  },
  5: {
    run: btn5Function,
    endEvent: btn5FunctionEndEvent
  }
}

// 统一绑定所有按钮的点击事件
$('[id^="btn"]').on('click', function () {
  const btnId = this.id.replace('btn', '')
  // 先清除所有按钮的激活状态,再给当前按钮加激活
  $('[id^="btn"]').removeClass('active')
  $(this).addClass('active')
  // 执行按钮对应的函数
  btnMap[btnId].run()
})

// 统一绑定所有结束事件
Object.entries(btnMap).forEach(([id, config]) => {
  config.endEvent.on('end', () => {
    $(`#btn${id}`).removeClass('active')
    // 其他公共结束逻辑可统一在这里添加
  })
})

该版本改动最小,代码量相比原版本减少70%以上,后续新增按钮只需在btnMap中添加对应配置即可,不需要重复写事件绑定代码。


面向对象封装版

如果需要更高的复用性、可扩展性,可以用面向对象的方式把整个按钮组的逻辑封装成类:

class ActionButtonGroup {
  /**
   * @param {string} selector 按钮的通用选择器
   * @param {object} config 按钮配置表
   */
  constructor(selector, config) {
    this.selector = selector
    this.config = config
    this.init()
  }

  // 初始化事件绑定
  init() {
    this.bindClick()
    this.bindEndEvents()
  }

  // 绑定点击事件
  bindClick() {
    $(this.selector).on('click', (e) => {
      const $currentBtn = $(e.currentTarget)
      const btnId = $currentBtn.attr('id').replace('btn', '')
      this.clearAllActive()
      $currentBtn.addClass('active')
      this.config[btnId].run()
    })
  }

  // 清除所有按钮激活状态
  clearAllActive() {
    $(this.selector).removeClass('active')
  }

  // 绑定所有结束事件
  bindEndEvents() {
    Object.entries(this.config).forEach(([id, cfg]) => {
      cfg.endEvent.on('end', () => {
        $(`#btn${id}`).removeClass('active')
      })
    })
  }

  // 可扩展方法:动态新增按钮
  addBtn(btnId, btnConfig) {
    this.config[btnId] = btnConfig
    this.bindClick()
    this.bindEndEvents()
  }

  // 可扩展方法:批量禁用所有按钮
  disableAll() {
    $(this.selector).prop('disabled', true)
  }
}

// 调用示例
const btnConfig = {
  1: { run: btn1Function, endEvent: btn1FunctionEndEvent },
  2: { run: btn2Function, endEvent: btn2FunctionEndEvent },
  3: { run: btn3Function, endEvent: btn3FunctionEndEvent },
  4: { run: btn4Function, endEvent: btn4FunctionEndEvent },
  5: { run: btn5Function, endEvent: btn5FunctionEndEvent }
}
const btnGroup = new ActionButtonGroup('[id^="btn"]', btnConfig)

该版本的优势在于逻辑完全封装,和业务代码解耦,支持多实例复用,后续如果需要添加批量操作、状态查询等功能,直接在类中添加方法即可,维护成本极低。

注:原代码存在语法错误,$("#btn3)、$("#btn3)两处漏了右引号,优化时已修复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 00:15:04