繁体   English   中英

如何删除带有动态标题的 HTML 列<th>姓名

[英]How to delete HTML column with dynamic header <th> name

我有一个能够将新列添加到 HTML 表的脚本。 当用户按下add group ,标题将变为Group1Group2等等.. 目前我正在添加一个delete group功能,能够删除所有添加的列。 所以现在的问题是当我删除一个列并再次添加一个新列时,名称Group(x)不会被重置。

例如:用户添加group1和group2,然后删除group2。 下次他再次按下添加组时,它将显示 group3 而不是 group2 图片:

在此处输入图片说明

预期输出:每当删除列时都应重置列名。

网址:

<table id="persons" border="1">
    <thead id="theadID">
        <tr>
            <th>Name</th>
            <th>sex</th>
            <th>Message</th>
        </tr>
    </thead>
    <tbody id="tbodyID">
        <tr>
            <td>Viktor</td>
            <td>Male</td>
            <td>etc</td>
        </tr>
        <tr>
            <td>Melissa</td>
            <td>Female</td>
            <td>etc</td>
        </tr>
        <tr>
            <td>Joe</td>
            <td>Male</td>
            <td>etc</td>
        </tr>
    </tbody>
</table>

<button onclick="javascript:appendColumn()">Add column</button>

<input type="button" onclick="deleteLastColumn();" value="do it"/>

jQuery & Javascript:

function deleteLastColumn() {
    $('#persons tr').find('th:last-child, td:last-child').remove()
}


        let groupNum = 1;
const tableEl = document.getElementById('persons');

// append column to the HTML table
function appendColumn() {

  // open loop for each row and append cell
  for (let i = 0; i < tableEl.rows.length; i++) {
    createCell(tableEl.rows[i].insertCell(tableEl.rows[i].cells.length), i, 'col');
  }

  tableEl.rows[0].querySelector('td:last-child').textContent = 'Group' + groupNum;
  groupNum++;
}

// create DIV element and append to the table cell
function createCell(cell, text, style) {
  var div = document.createElement('div'), // create DIV element
    txt = document.createTextNode(text); // create text node
  div.appendChild(txt); // append text node to the DIV
  div.setAttribute('class', style); // set DIV class attribute
  div.setAttribute('className', style); // set DIV class attribute for IE (?!)
  cell.appendChild(div); // append DIV to the table cell
}


也许我错过了它,但我没有看到删除所有列的代码,我只看到了一个。 但解决方案似乎仍然很简单,只需在删除 col 时减少groupNum变量

function deleteLastColumn() {
    $('#persons tr').find('th:last-child, td:last-child').remove()
    groupNum--;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM