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

使用jQuery根据选中房间数量自动计算总费用的异常问题求助

问题根源

现有代码每次触发下拉框change事件时,直接将当前选中值累加到全局总房间数、总费用中,没有记录单个下拉框的历史选中值,因此无法处理选中值调低的场景,就会出现原选2后改1、总房间数变成3的异常。

解决方案

推荐两种实现方式,优先选择第一种,逻辑更简洁不易出错:

方案1:每次change遍历全量下拉框重新计算

该方案不需要记录历史值,每次用户修改任意下拉框时,重新统计所有房型的选中数量和对应费用,直接覆盖更新全局值即可,后续新增房型也不需要调整统计逻辑。

$(document).ready(function() {
  $(".quantity").on('change', function() {
    let totalRooms = 0;
    let totalCost = 0;
    // 遍历所有房型下拉选择框统计
    $(".quantity").each(function() {
      const roomCount = parseInt($(this).val()) || 0;
      const perCost = parseInt($(this).parent().parent().find('.charge p').text()) || 0;
      totalRooms += roomCount;
      totalCost += roomCount * perCost;
    })
    // 直接更新全局统计值
    $('.room_no').val(totalRooms);
    $('.total_cost').val(totalCost);
  });
})

方案2:记录单个下拉框旧值,通过差值更新

如果需要实现“判断选中值是否调低”的需求,可以给每个下拉框绑定自定义属性存储上一次的选中值,每次change时计算新旧值的差值再更新全局统计,差值小于0即代表选中值被调低:

$(document).ready(function() {
  // 初始化每个下拉框的旧值为0
  $(".quantity").each(function() {
    $(this).data('oldVal', 0);
  })
  $(".quantity").on('change', function() {
    const oldVal = $(this).data('oldVal');
    const newVal = parseInt($(this).val()) || 0;
    const perCost = parseInt($(this).parent().parent().find('.charge p').text()) || 0;
    // 计算新旧值差值
    const diffCount = newVal - oldVal;
    const diffCost = diffCount * perCost;
    // 更新全局统计
    $('.room_no').val(parseInt($('.room_no').val()) + diffCount);
    $('.total_cost').val(parseInt($('.total_cost').val()) + diffCost);
    // 更新当前下拉框的旧值记录
    $(this).data('oldVal', newVal);
  });
})

内容的提问来源于stack exchange,提问作者The Only Smart Boy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 18:54:01