如何在动态JavaScript表格中管理带唯一分隔符的同类型子服务多实例
问题修复:同类型子服务实例添加后被覆盖的问题
问题现象
开发的Web应用允许用户向表格添加同类型子服务的多个实例,每个实例需生成带独立名称的分隔符。但添加同类型但不同名称的子服务时,仅显示最后一个实例的名称,之前实例的行项全部消失。已尝试为每个实例生成唯一ID,但问题依旧。
核心问题分析
从代码来看,问题出在两处关键逻辑:
- 分隔符判断仅依赖服务类型和名称,同类型不同实例的服务类型一致,新实例名称变更时会覆盖旧分隔符的判断逻辑,导致旧实例行项被误判为重复而不显示。
- 分隔符行未绑定对应实例的唯一ID,后续无法精准区分或更新不同实例的分隔符。
- 名称更新事件未传入实例唯一ID,无法定位到对应分隔符进行修改。
修复步骤
1. 为分隔符行绑定唯一实例ID
修改loadLeistungsverzeichnis中生成分隔符的代码,添加data-subservice-instance-id属性,关联到当前实例的唯一标识:
const separatorRow = document.createElement('tr'); separatorRow.classList.add('table-secondary'); // 绑定实例唯一ID separatorRow.dataset.subserviceInstanceId = lv.subservice_instance_id; separatorRow.innerHTML = `<td colspan="7">Teilleistung ${currentTeilleistung} - ${currentTeilleistungName}</td>`; lvBody.appendChild(separatorRow);
2. 基于实例ID修改分隔符判断逻辑
将分隔符的判断条件从服务类型+名称改为实例唯一ID,确保每个实例的分隔符独立:
// 替换原有判断变量 let currentSubserviceInstanceId = ''; data.forEach(lv => { if (!existingLvIds.has(lv.id.toString())) { // 基于实例ID判断是否需要新增分隔符 if (lv.subservice_instance_id !== currentSubserviceInstanceId) { currentSubserviceInstanceId = lv.subservice_instance_id; currentTeilleistung = lv.teilleistung; currentTeilleistungName = lv.teilleistung_name; const separatorRow = document.createElement('tr'); separatorRow.classList.add('table-secondary'); separatorRow.dataset.subserviceInstanceId = lv.subservice_instance_id; separatorRow.innerHTML = `<td colspan="7">Teilleistung ${currentTeilleistung} - ${currentTeilleistungName}</td>`; lvBody.appendChild(separatorRow); } // 创建并添加服务行 const row = createLvRow(lv, false); lvBody.appendChild(row); } });
3. 修复名称更新事件的参数传递
修改addNewSubService中的事件监听,传入实例唯一ID,确保updateTeilleistungName能定位到对应分隔符:
// 替换原事件监听代码 const nameElement = document.getElementById(`${service}-name-${index}-${subserviceInstanceId}`); if (nameElement) { nameElement.addEventListener('input', () => updateTeilleistungName(service, index, subserviceInstanceId)); }
4. 精准定位分隔符进行更新
修改updateTeilleistungName的选择器,通过实例ID精准定位对应分隔符:
function updateTeilleistungName(service, index, uniqueId) { const serviceName = document.getElementById(`${service}-name-${index}-${uniqueId}`).value; console.log(`Updating teilleistung name: ${serviceName} for service: ${service}, index: ${index}, uniqueId: ${uniqueId}`); // 通过实例ID定位分隔符 const separatorRow = document.querySelector(`tr.table-secondary[data-subservice-instance-id="${uniqueId}"]`); if (separatorRow) { separatorRow.innerHTML = `<td colspan="7">Teilleistung ${serviceName}</td>`; } }
5. 验证API返回数据
确保后端API返回的每个lv对象都正确包含subservice_instance_id字段,这是关联实例的核心标识,缺失该字段会导致所有关联逻辑失效。
内容的提问来源于stack exchange,提问作者Daywalker
相关产品推荐
相关产品推荐

