javascript - 在第 n 个位置添加新列 Javascript

标签 javascript html datatable multiple-columns

我正在尝试在第 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/

相关文章:

c# DataGridView 从行/列获取内容

javascript - 使用 ajax 调用(ajax 和 for)时获取数据的问题

javascript - HTML 样式表相互干扰

html - 在Vuetify中将文本对齐到文本字段的中心

javascript - 根据下拉选择添加 Bootstrap 字段

html - 如何将导出按钮添加到 html/jquery 数据表代码中?

javascript - jquery 数据表搜索显示已删除的数据

javascript - typescript中数组的两种写法有什么区别

javascript - ready() 是否异步执行?

html - 在 html 和 CSS 中定位 div