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

JavaScript实现颜色、尺寸两组按钮选中值相加显示总价

实现商品规格叠加计价功能

你当前写的代码逻辑本身已经可以实现你要的计价效果:

  • 白色基础定价40、黑色基础定价50
  • 小码加价1、中码加价5
  • 两者相加刚好完全匹配你列出的四个组合价格:
    • White + Small = 40 + 1 = 41
    • Black + Small = 50 + 1 = 51
    • White + Medium = 40 + 5 = 45
    • Black + Medium = 50 + 5 = 55

不过现有代码重复逻辑太多,后续如果要加新的颜色、尺寸,需要重复写很多结构相似的函数,维护起来很麻烦,可以做如下优化:

优化后完整代码

JavaScript 部分

// 统一维护所有规格的加价规则,后续改价、加新规格只需要改这里
const priceMap = {
  color: {
    white: 40,
    black: 50
  },
  size: {
    small: 1,
    medium: 5
  }
}
// 存储用户当前选中的规格对应价格
let currentSelected = {
  color: 0,
  size: 0
}

// 统一计算总价并更新页面展示
function refreshPrice() {
  const total = currentSelected.color + currentSelected.size
  const priceDom = document.getElementById('current-price')
  priceDom.textContent = total ? `$${total}` : '请选择完整规格'
}

// 选择颜色时触发
function onColorChange(colorKey) {
  currentSelected.color = priceMap.color[colorKey]
  refreshPrice()
}

// 选择尺寸时触发
function onSizeChange(sizeKey) {
  currentSelected.size = priceMap.size[sizeKey]
  refreshPrice()
}

HTML 部分

<div>当前价格:<span id="current-price">请选择完整规格</span></div>

<div class="color-select">
  <button type="button" onclick="onColorChange('white')">White</button>
  <button type="button" onclick="onColorChange('black')">Black</button>
</div>

<div class="size-select">
  <button type="button" onclick="onSizeChange('small')">Small</button>
  <button type="button" onclick="onSizeChange('medium')">Medium</button>
</div>

优化说明

  • 所有价格规则统一存在priceMap对象里,后续调整价格、新增规格不需要改动核心计算逻辑
  • 把重复的价格计算、DOM更新逻辑抽成单独的refreshPrice函数,减少冗余代码
  • 增加了未选全规格时的默认提示,避免用户看到0元的错误价格
  • 用textContent代替innerHTML设置纯文本内容,性能更好也能避免XSS风险

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 10:33:27