You need to enable JavaScript to run this app. 使用jQuery实现多输入框联动计算并按利润率阈值动态修改div背景色的方法
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery实现多输入框联动计算并按利润率阈值动态修改div背景色的方法

表单联动计算功能代码修正与实现

现有代码存在的具体问题

  • ID选择器匹配错误:HTML中天数输入框的实际ID为day,但JS取值时写的是#days,会导致取值结果为NaN
  • 选择符缺失:margin计算逻辑中获取client-price元素值时,写的是$("client-price"),缺少ID选择符#,无法正确取到元素值
  • 事件覆盖不全:client-price输入框支持手动修改,但没有纳入keyup监听范围,修改后不会触发margin值的重计算
  • 边界值未处理:当client_price为0时,执行除法运算会得到Infinity,直接填充到输入框会出现异常值
  • 缺失需求要求的动态样式切换逻辑,没有根据margin值修改.e类div的背景色

修正后的完整逻辑实现

核心思路:抽离统一的计算函数,避免重复代码,覆盖所有触发场景,加边界值兜底
首先需要把天数输入框的ID调整为和需求一致的days,解决ID不匹配问题(如果不想改HTML,也可以后续在JS取值时对应匹配#day),修正后的HTML片段如下:

<div class="a calc"><label>Rate</label><input id="rate" name="rate" type="text"></div>
<div class="b calc"><label>Days</label><input id="days" name="day" type="text" ></div>
<div class="c calc-two">
  <label>Client Price</label>
  <input id="client-price" name="client-price" type="text">
</div>
<div class="d calc-two">
  <label>My price</label>
  <input id="my-price" name="my-price" type="text">
</div>
<div class="e"><label>Margin</label><input id="margin" name="margin" type="text" value=""></div>

对应的修正后JS代码:

// 统一计算入口
function runCalc() {
  // 取值并做数字类型转换,空值/非数字内容统一兜底为0
  const rate = parseFloat($("#rate").val()) || 0;
  const days = parseFloat($("#days").val()) || 0;
  const myPrice = parseFloat($("#my-price").val()) || 0;

  // 计算客户价格,向上取整
  const clientPrice = Math.ceil(rate * days);
  $("#client-price").val(clientPrice);

  // 计算margin值,除零场景兜底为0
  const margin = clientPrice === 0 ? 0 : Math.ceil((myPrice * 100) / clientPrice);
  $("#margin").val(margin);

  // 动态切换.e元素的背景色
  const $targetEl = $(".e");
  if (margin > 50) {
    $targetEl.css("background", "red");
  } else {
    $targetEl.css("background", "green");
  }
}

// 绑定所有相关输入框的keyup事件,包含手动修改client-price的场景
$("#rate, #days, #client-price, #my-price").on("keyup", runCalc);

实现效果说明

  • 输入rate、days的值后,会自动计算乘积向上取整填充到client-price输入框
  • 不管是自动生成的client-price值,还是用户手动修改的client-price值,只要值发生变化,就会重新计算margin值并填充
  • 每次margin值更新时,会自动判断大小,同步切换.e元素的背景色:高于50%为红色,其余为绿色
  • 输入空值、非数字内容时,不会出现NaN、Infinity这类异常值,会自动按0处理计算

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.30 12:36:02