我正在尝试在第 n 个位置动态添加一个新列。目前,请在下面找到我的代码。
var name = window.prompt("Please enter the Column Name you intend to Add", "");
var name2 = window.prompt("Please enter the Column Location you intend to Add", "");
if (name == null || name.trim() == "" || name == "0") {
alert('Invalid Column Number');
}
else if (name2 == null || name2.trim() == "" || name2 == "0") {
alert('Invalid Column Number');
}
else {
var name1 = parseInt(name2);
$('td:nth-child(' + name1 + ')').append($("<td>"));
$('th:nth-child(' + name1 + ')').html(name).css("font-weight", "Bold");
}
HTML 标记
<div class="table-responsive" style="margin-top:10px;">
<table class="table table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th>Sl No</th>
<th>Item Id</th>
<th>Item Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr id="mainid">
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
<td><input type="text"/></td>
</tr>
</tbody>
</table>
</div>
我能够成功添加新列,但这会替换现有列。我需要的是附加到索引编号的列,但它会替换它。谁能指导解决这个问题。
最佳答案
将它插入之前
您在索引中找到的td
,而不是追加
$('td:nth-child(' + name1 + ')').insertBefore($("<td>"));
您正在附加 td
,这实际上会将 td
添加为找到的 td
的子级,而不是兄弟级
还有一个建议
我还认为您也应该运行这一行来为您的新列添加标题
$('th:nth-child(' + name1 + ')').insertBefore($("<th>"));
关于javascript - 在第 n 个位置添加新列 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37389922/