表格每行添加Remove Button异常求助:按钮仅显示在最后一行
问题原因
你只创建了一个removeButton元素,而DOM中的元素实例不能同时挂载在多个父节点下。每次执行titleCell.appendChild(removeButton)时,浏览器会把这个按钮从之前的行里“挪”到当前循环的行中,所以最后只有最后一行能显示按钮。
解决方法
把按钮的创建逻辑放到forEach循环内部,每处理一行就新建一个独立的按钮:
修改后的代码:
function updateTable() { table.innerHTML = "<tr><th>Title</th><th>Author</th><th>Pages</th><th>Is read?</th></tr>"; if (myLibrary.length != 0) { const tableContent = document.createDocumentFragment(); myLibrary.forEach((value) => { const tableRow = document.createElement("tr"); const titleCell = document.createElement("td"); const title = document.createElement("p"); const author = document.createElement("td"); const pages = document.createElement("td"); const isRead = document.createElement("td"); // 每行单独创建移除按钮 const removeButton = document.createElement("button"); removeButton.innerText = "Remove book"; removeButton.className = "table__remove-btn"; title.innerText = value.title; titleCell.appendChild(title); titleCell.appendChild(removeButton); titleCell.className = "table__title-cell"; tableRow.appendChild(titleCell); author.innerText = value.author; tableRow.appendChild(author); pages.innerText = value.pages; tableRow.appendChild(pages); isRead.innerText = value.isRead ? "Yes" : "No"; tableRow.appendChild(isRead); tableContent.appendChild(tableRow); }); table.appendChild(tableContent); } }
这样每一行都会生成属于自己的移除按钮,不会出现按钮“乱跑”的情况。
内容的提问来源于stack exchange,提问作者Tomas Malleret
相关产品推荐
相关产品推荐

