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

jQuery函数间调用如何传递变量?实现产品选择联动价格计算

解决jQuery函数间传递tableRow变量的问题

核心思路很直接:把price函数改成支持接收外部传入的tableRow参数,这样在product_selection里拿到当前行的DOM元素后,直接传进去调用就行,不用再触发change事件浪费性能。

1. 重构price函数,兼容参数传入

原来的price函数应该是通过触发事件的元素去查找父行,现在改成优先使用传入的tableRow参数,没有参数时再沿用原有逻辑,既不破坏原来数量变更触发计算的功能,又支持主动调用传参:

function price(tableRow) {
  // 优先用传入的行元素,没有的话从事件触发元素获取
  const $targetRow = tableRow ? $(tableRow) : $(this).closest('tr');
  
  // 保留你原来的价格计算逻辑
  const product = $targetRow.find('.product-select').val();
  const quantity = parseInt($targetRow.find('.quantity-input').val()) || 0;
  
  // 替换成你实际的价格计算代码
  const calculatedPrice = getProductPrice(product) * quantity;
  
  // 更新行内的价格显示
  $targetRow.find('.price-display').text(calculatedPrice.toFixed(2));
}

2. 在product_selection里直接调用price并传参

当产品选择变更时,先设置默认数量,然后把当前的tableRow直接传给price函数:

function product_selection() {
  // 获取当前操作的表格行
  const $currentRow = $(this).closest('tr');
  
  // 保留你原来设置参考值的逻辑
  const selectedProduct = $(this).val();
  setReferenceValue($currentRow, selectedProduct);
  
  // 设置默认数量(比如默认1,按需调整)
  $currentRow.find('.quantity-input').val(1);
  
  // 直接调用price,把当前行传进去
  price($currentRow);
}

3. 保留原有事件绑定

原来的数量输入框绑定逻辑不用改,重构后的price函数会自动适配:

// 数量变更时触发价格计算(原有逻辑不变)
$('.quantity-input').on('change', price);

// 产品选择变更时触发逻辑
$('.product-select').on('change', product_selection);

这样既避免了触发额外DOM事件带来的性能损耗,又完美实现了产品选择后自动设默认数量并计算价格的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 00:30:43