javascript - 使用 javascript/jQuery 插入新行时,如何向每个表行插入 "remove button"

标签 javascript jquery html

我更喜欢使用 javascript 来完成它,但如果 jQuery 最简单,那么我会使用它。我只是不太了解 jQuery。我目前的 HTML 表格是:

<table id = "liftTable" border="1" rules="rows">
<caption><b>Today's Workout</b></caption>
<tr>
 <th align="left" width="150">Lift Name</th>
 <th align="left" width="90">Weight (lbs)</th>
</tr>
<tr>
  <td>Bench Press</td>
  <td>2000</td>
  <td><input name="btnRemoveItem" type="button" id="btnRemoveItem" value="Remove Lift" onclick="removeListItem(this)"/></td>
</tr>
<tr>
 <th align="left">Total:</th>
 <td class="sum">0</td>
</tr>
</table>

该表已经有一个示例,显示我希望如何设置每个新行。这是我的“添加行”javascript:

function addTableRow(){
var iteration = 1;
var table = document.getElementById("liftTable");
var rowCount = table.rows.length - 2;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = document.getElementById("Form1").value;
cell2.innerHTML = document.getElementById("numOfSets").value;
var bt = document.getElementById("btnRemoveItem");
cell3.appendChild(bt);
}

最大的问题是当我尝试创建“var bt = document.getElementById("btnRemoveItem");”时并尝试将其插入到 cell3 中。我真的不知道如何以其他方式实现这一目标。感谢您的帮助。

最佳答案

当您尝试在不同位置多次向 DOM 添加相同的精确元素对象时,浏览器通常不喜欢它。

尝试这样做,并注意您可能必须处理页面上具有相同元素 ID 的多个元素:

var bt = document.getElementById("btnRemoveItem").cloneNode();

关于javascript - 使用 javascript/jQuery 插入新行时,如何向每个表行插入 "remove button",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21102004/

相关文章:

jquery - 如何在没有提交按钮的情况下使用 Enter 键提交表单

c# - 寻呼机 HTML 查看器

javascript - 如何在 React/React-Native 中类型检查嵌套参数

javascript - 未捕获的类型错误 : Cannot read property '_myPrivateFunction' of undefined

javascript - 如何使用 javascript (jquery) 替换列表中图像的 src?

javascript - 使用 jQuery 的 $.getScript(),我可以检测到 304 Not Modified headers 吗?

javascript - jquery ui Accordion 避免在单击另一个项目时关闭项目

javascript - 如何获取大div的html

javascript - Alfresco - JavaScript API(根对象)和 JavaScript 服务 API 之间的区别

javascript - 多行正则表达式无法正常工作