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

MySQL数据库多表格行场景下如何通过选择获取动态价格值

问题根因

  • 变量作用域错误:myItemPrices 函数中使用的 i 是 addRow 函数内的局部变量,函数外部无法访问,导致选择器无法匹配到对应行的元素
  • data-* 属性命名混乱:新增行的商品选项用了动态生成的 data-prices+序号 属性,每个商品的价格属性名不统一,无法通用取值
  • 逻辑冗余:单独写了两套价格赋值函数,维护成本高

修复方案

1. 统一价格数据属性命名

修改 fill_unit_select_box 函数,把动态生成的属性名改成固定的 data-price:

function fill_unit_select_box($conn)
{ 
    $query_item = "SELECT * from gs_items ORDER BY item_name ASC";
    $result_item = $conn->query($query_item);
    foreach($result_item as $rows)
    {    
        echo '<option data-price="'.$rows['price'].'" value="'.$rows['Id'].'">'.$rows['item_name'].'</option>';
    }
}

2. 修改事件触发逻辑,传递行号参数

  • 第一行的select标签修改onchange属性:onchange="myItemPrice(1)"
  • addRow 函数中新增行的select标签onchange属性修改为:onchange="myItemPrice(${i})"

3. 统一价格赋值函数

删掉原来的 myItemPrices 函数,保留一个通用的价格赋值函数即可:

function myItemPrice(rowNum){
    // 兼容第一行和新增行的ID命名规则
    const selectId = rowNum === 1 ? 'selected_item' : `selected_items${rowNum}`;
    const priceInputId = rowNum === 1 ? 'getprice' : `getprices${rowNum}`;
    const price = $(`#${selectId}`).find(':selected').data('price');
    $(`#${priceInputId}`).val(price);
}

可选优化

统一价格输入框状态

第一行价格输入框是禁用状态,若要和新增行保持一致,可修改新增行的价格输入框代码:

html +='<td > <input type="number" name="getprices'+i+'" style="font-size: 12px; color: #333333;" id="getprices'+i+'" disabled ></td>';

补充删除行功能

你当前的remove函数未实现,可补充如下代码:

function remove(btn){
    // 删除当前行
    $(btn).closest('tr').remove();
    // 重新计算行号避免序号混乱
    $('#customFields tr').each(function(index){
        $(this).find('td:first').text(index + 1);
    })
}

同时修改新增行的删除按钮调用代码:

html +='<td><button onclick="remove(this);">Remove</button></td>';

界面示意图

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:42:02