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

可编辑表格点击所有编辑按钮后下拉框均显示最后选中值问题求助

问题根因

  • 全局变量污染:valSelect、value01、value02没有加let/const声明,默认挂载为全局变量,每次点击编辑按钮都会覆盖这个全局值,后续给所有下拉框赋值时用的都是最后一次覆盖的值。
  • ID重复违反HTML规范:页面ID必须唯一,你每次生成下拉框都用固定IDselectOption,导致document.querySelectorAll("#selectOption")会选中页面所有已经生成的下拉框,每次点击某一行编辑,都会给所有行的下拉框重新加载选项。
  • 未设置下拉框默认选中值:ajax加载完品牌选项后,没有根据当前行原有品牌名设置对应的option为选中状态。
  • 多余的全局遍历:点击单行编辑时不需要处理所有行的下拉框,只需要处理当前点击行的下拉框即可。

修正后的代码

function editBtn(event) {
    // 声明局部变量,避免全局污染
    const editTr = event.currentTarget.parentElement.parentElement.parentElement;
    const al = $(editTr).find(".companyValue0")
    const valName = $(editTr).find(".companyValue1")
    const valMail = $(editTr).find(".companyValue2")
    // 声明为局部变量
    const valSelect = al.text()
    const value01 = valName.text();
    const value02 = valMail.text();
    
    // 去掉固定ID,改用class标识,避免ID重复
    const select = `<select class="form-control select-option"></select>`
    const inputName = `<input class="form-control" value="${value01}" />`
    const inputMail = `<input class="form-control" value="${value02}" />`
    valName.html(inputName)
    valMail.html(inputMail)
    al.html(select);
    
    // 只获取当前行的下拉框,不要查询全局所有的
    const currentSelect = al.find('.select-option')[0]
    ajaxBrand(currentSelect, valSelect)
    setButtonsEdit(event)
}

function ajaxBrand(opt, value) {
    $.ajax({
        type: "POST",
        url: '{{ path('brand_selection') }}',
        dataType: 'json',
        // 注意:原代码里的name变量未定义,请根据实际业务补充参数
        data: {
            name: name,
        },
        success: function (data) {
            const brandName = data.brands
            let optionsHtml = ''
            for(let i = 0 ; i < brandName.length ; i++) {
                // 判断当前品牌名是否等于传入的默认值,加selected属性
                const selected = brandName[i].name === value ? 'selected' : ''
                optionsHtml += `<option value="${brandName[i].id}" ${selected}>${brandName[i].name}</option> `
            }
            opt.innerHTML = optionsHtml
        },
        error: function (response) {
            return false;
        }
    })
}

额外注意点

原代码中ajax请求的data参数里的name变量未定义,请根据你的实际业务需求补充对应参数值,否则请求会报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 03:12:01