如何在DOM中更新同一员工不同周次的JSON排班记录
解决排班表DOM更新只命中第一条记录的问题
问题出在HTML元素ID的唯一性上:你现在给每条克隆记录设置的ID是record.employid,但同一个员工的两周记录会重复使用这个ID——而HTML规范里ID必须是全局唯一的,所以jQuery的$("#"+record.employid)只会匹配到DOM中第一个出现的元素,这就是后续记录无法更新的原因。
下面是具体的修复步骤:
1. 修正克隆记录的ID生成规则
把员工ID和周起始日期结合起来,生成全局唯一的ID。注意日期里的特殊字符(比如/)不能直接用在ID里,需要先替换成合法字符(比如-):
$.each(jsondata, function(i, record) { // 先处理周起始日期,替换非法字符 const safeWeekStart = record.weekstart.replace(/\//g, "-"); const uniqueRecordId = `${record.employid}-${safeWeekStart}`; if (!document.getElementById(uniqueRecordId)) { // Clone records begin var recordDetailCloned = $('.recordid').first().clone().show(); // 设置唯一ID recordDetailCloned.attr("id", uniqueRecordId); // 额外添加数据属性,方便后续定位(可选但推荐) recordDetailCloned.attr({ "data-employid": record.employid, "data-weekstart": record.weekstart }); recordDetailCloned.find('.weekstart').text(record.weekstart); recordDetailCloned.find('.shift').text(record.shift); recordDetailCloned.find('.employid').text(record.employid); recordDetailCloned.find('.name').text(record.name); recordDetailCloned.find('.mon').text(record.mon); recordDetailCloned.find('.tue').text(record.tue); recordDetailCloned.find('.wed').text(record.wed); } $('.start-card').append(recordDetailCloned); });
2. 更新记录时精准定位
你可以选择两种方式定位目标元素:
方式一:用新的唯一ID定位
$.each(jsondata, function( i, record ) { const safeWeekStart = record.weekstart.replace(/\//g, "-"); const targetRecord = $(`#${record.employid}-${safeWeekStart}`); targetRecord.find('.weekstart').text(record.weekstart); targetRecord.find('.shift').text(record.shift); targetRecord.find('.employid').text(record.employid); targetRecord.find('.mon').text(record.mon); targetRecord.find('.tue').text(record.tue); targetRecord.find('.wed').text(record.wed); });
方式二:用数据属性定位(更灵活)
如果后续ID规则有变化,数据属性的方式不需要修改选择器逻辑:
$.each(jsondata, function( i, record ) { // 通过员工ID和周起始日期的组合属性定位 const targetRecord = $(`[data-employid="${record.employid}"][data-weekstart="${record.weekstart}"]`); targetRecord.find('.weekstart').text(record.weekstart); targetRecord.find('.shift').text(record.shift); targetRecord.find('.employid').text(record.employid); targetRecord.find('.mon').text(record.mon); targetRecord.find('.tue').text(record.tue); targetRecord.find('.wed').text(record.wed); });
3. 修正模板中的重复ID问题
你的模板里多个元素用了id="day",这也是违反HTML规范的,克隆后会生成大量重复ID的元素,可能引发其他问题。建议把这些ID去掉,只保留class:
<div class="recordid" id="recordid" style="display:none;"> <div class="container"> <div class="weekstart"></div> <div class="shift-cell shift">Shift</div> <div class="name-cell employid">employid</div> <div class="name-cell name">Name</div> <div class="day-cell mon">Mon</div> <div class="day-cell tue">Tue</div> <div class="day-cell wed">Wed</div> </div><!-- Clone template container End --> </div> <!-- Recordid END -->
这样修改后,每个员工的两周记录都会有唯一的标识,更新时就能精准命中对应的DOM元素了。
内容的提问来源于stack exchange,提问作者Jvaskana
相关产品推荐
相关产品推荐

