簡體   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