修改模板表格ID后,使用jQuery append()添加行失效问题
问题描述
我通过模板生成多个表格,为避免填充表格时出现混乱,会在获取模板后修改表格ID。但修改ID后,使用jQuery的append()方法填充表格时,表格始终为空;若不修改ID则能正常填充。相关代码如下:
HTML代码
<template id="ticket-card"> <div id="ticket-line" class="ticketCard"> <div class="ticketTitle ticket-container"></div> <div class="ticketUser ticket-container"></div> <div class="tickeDate ticket-container"></div> <div class="ticketMessage ticket-container"></div> <div class="ticketButton buttonsContainer"> <div class="pre-toggle"> <label class="toggle"> <input type="checkbox" id="is-resolved"> <span class="labels" data-on="Resolu" data-off="En cours"></span> </label> </div> <button id="reply-msg" class="buttonReply"><img src="../../rsc/reply.png" alt="Répondre" class="replyIcon"></button> <button id="delete-msg" class="buttonDelete"><img src="../../rsc/trash.png" alt="Supprimer" class="trashSign"/></button> </div> </div> <div class="containerScrollable response" id="containerResponse"> <table> <tbody id="Tableresponse"> <tr></tr> </tbody> </table> </div> </template>
jQuery/TypeScript代码
let UserElement = <HTMLElement>templateElement.content.cloneNode(true); let idx; for (idx = 0; idx < 4; idx++) { UserElement.querySelector("#Tableresponse").setAttribute("id", "Tableresponse" + idx); $('#Tableresponse' + idx).children().detach(); $('#Tableresponse' + idx).append("<tr><td>Hello</td></tr><tr><td>World!</td></tr>");
解决方案
问题核心是修改ID后的DOM元素还未被添加到页面DOM树中,jQuery选择器无法定位到这个元素,所以填充操作无效。
正确的处理流程:
- 每次循环都重新克隆模板内容,避免复用同一个DOM片段导致ID冲突或元素状态异常
- 先对克隆后的tbody元素填充内容,再修改其ID
- 最后把整个模板片段插入到页面的目标容器中
调整后的代码示例:
// 获取模板元素 const templateElement = document.getElementById('ticket-card'); if (!templateElement) return; // 假设页面中有一个用来承载生成内容的容器,ID为ticket-wrapper const ticketWrapper = document.getElementById('ticket-wrapper'); if (!ticketWrapper) return; for (let idx = 0; idx < 4; idx++) { // 每次循环克隆新的模板内容 const clonedElement = <HTMLElement>templateElement.content.cloneNode(true); // 获取当前克隆的tbody元素 const tbody = clonedElement.querySelector("#Tableresponse"); if (!tbody) continue; // 先清空原有内容并填充新数据 tbody.innerHTML = ''; tbody.insertAdjacentHTML('beforeend', "<tr><td>Hello</td></tr><tr><td>World!</td></tr>"); // 修改为唯一ID tbody.setAttribute("id", `Tableresponse${idx}`); // 将整个克隆片段添加到页面容器 ticketWrapper.appendChild(clonedElement); }
额外注意事项:
- 模板内的其他ID(如
ticket-line、is-resolved、reply-msg)在循环克隆后也会重复,后续绑定事件或操作时会出现冲突,建议改为类名,或者同样在克隆时生成唯一ID - 尽量统一使用原生DOM操作或jQuery,减少不同API混用带来的调试成本
内容的提问来源于stack exchange,提问作者Riana
相关产品推荐
相关产品推荐

