javascript - 如何使用JS在特定列之前添加列

标签 javascript

enter image description here

我可以从选择标签中获取列索引。选择标记选项是从我从表格标题行获取的数组中填充的。

我有代码在表中最后一列之后添加列。

我必须如何更改代码才能在特定列索引后添加列?

在选择标签发生变化时,我得到列索引。

 var arrHead = new Array(); // array for header.
document.getElementById("add-i-tableID").addEventListener("click", function(){
   
    arrHead = [ 'Customer', 'Article', 'Amount'];
  
        var empTable = document.createElement('table');
        empTable.setAttribute('id', 'empTable'); // table id.

        var tr = empTable.insertRow(-1);
        for (var h = 0; h < arrHead.length; h++) {
            var th = document.createElement('th'); // create table headers
            th.innerHTML = arrHead[h];
            th.style.border= '1px solid ';
            tr.appendChild(th);
        }

        var div_table = document.getElementById('i_tableID');
        div_table.appendChild(empTable);  // add the TABLE to the container.
   
});var selectedIndexT = 0;
document.getElementById("add-i-colID").addEventListener("click", function() {
  var th = document.createElement('th'); // create table headers
  var colname1 = prompt("Please enter name of  the column");
  th.innerHTML = colname1;
  th.style.border = '1px solid';

  var xcvbn = document.getElementById('empTable');
  var xcvbnR = xcvbn.getElementsByTagName("tr");
  xcvbnR[0].appendChild(th);

  for (i = 1; i < xcvbnR.length; i++) {
    var td = document.createElement('td');
    var ele1 = document.createElement('input');
    ele1.setAttribute('type', 'text');
    ele1.setAttribute('value', '');
    ele1.style.color = "#8dbeb6";
    td.appendChild(ele1);
    xcvbnR[i].appendChild(td);
  }
});
  <button id="add-i-tableID">Add test table</button>
 <button id="add-i-colID">Add column</button>

 <div id="i_tableID" ></div>

最佳答案

您可以使用Node.insertBefore

  • 单击Add按钮时,获取selectedIndex

    • 如果为0,则会发出警报,要求用户选择有效的列。
    • 如果它是有效索引,则要求用户提供列名称,然后使用提供的列名称创建第 元素。
  • 现在,获取表格、标题行 (thead tr) 以及标题行内的所有第 th 元素。

  • 接下来,使用 insertBeforeselectedIndex 将新创建的 th 插入到适当的位置。

  • 最后抓取所有正文行,并使用相同的逻辑在所有正文行的正确位置插入空 td 元素。

  • 然后您可以更新下拉列表中的选项。

document.querySelector("form").addEventListener("submit", function(e) {
  e.preventDefault();

  // Get the selected index
  const selIdx = document.querySelector("#add-col").selectedIndex;

  // If selected index is zero throw an alert
  if (!selIdx) return alert("Please select a column");

  // Ask for the column name
  const colName = prompt("Enter column name");

  // Create a `th` with the provided column name
  const th = document.createElement("th");
  th.innerText = colName;

  // Grab necessary elements from the DOM
  const table = document.querySelector("table");
  const tr = table.querySelector("thead tr");
  const allHeaders = table.querySelectorAll("th");

  // Insert the `th` at appropriate location
  tr.insertBefore(th, allHeaders[selIdx - 1]);

  // Fill body rows with empty `td` elements
  const tbody = table.querySelector("tbody");
  Array.from(tbody.children).forEach(function(row) {
    const emptyTd = document.createElement("td");
    row.insertBefore(emptyTd, row.children[selIdx - 1])
  })

  updateSelectOptions()
});

function updateSelectOptions() {
  const headers = document.querySelectorAll("table thead th");
  const select = document.querySelector("#add-col");

  // Empty the select node
  select.innerHTML = "";

  // Insert the default option
  const opt = document.createElement("option");
  opt.innerText = "Select a column";
  select.appendChild(opt)

  // Add other options based on the headers
  Array.from(headers).forEach(function(header) {
    const opt = document.createElement("option");
    opt.innerText = header.innerText;
    select.appendChild(opt)
  });
}
form * {
  display: block;
  margin: 0.75rem 0;
}

table {
  border-collapse: collapse;
}

table td,
table th {
  border: 1px solid #ddd;
  padding: 0.25rem 0.5rem;
}

table th {
  text-align: left;
  background-color: slateblue;
  color: #eee;
}
<table>
  <thead>
    <tr>
      <th>Customer</th>
      <th>Article</th>
      <th>Amount</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John</td>
      <td>Laptop</td>
      <td>1000</td>
    </tr>
    <tr>
      <td>Amanda</td>
      <td>Television</td>
      <td>750</td>
    </tr>
  </tbody>
</table>

<form>
  <label for="add-col">Add Column Before:</label>
  <select id="add-col">
    <option>Select a column</option>
    <option>Customer</option>
    <option>Article</option>
    <option>Amount</option>
  </select>
  <button>Add</button>
</form>

关于javascript - 如何使用JS在特定列之前添加列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67277936/

相关文章:

javascript - 在django模板中单击按钮时播放音频

javascript - Firebase 电子邮件验证工作流程

javascript - 如何以无点样式映射和过滤它

javascript - 在非 ajax 帖子中包含 json 数据

javascript - javascript 中的全局变量未按预期工作

javascript - 函数 getelementbyid 没有输出到正确的位置

javascript - querySelectorAll 和 getElementsBy* 方法返回什么?

javascript - 如何在Arbor js中鼠标悬停在节点上时显示节点的标签

javascript - 在 JavaScript 中从 url 中读取图像数据

javascript - 渲染后的 Preact 日志性能