我有一個能夠將新列添加到 HTML 表的腳本。當用戶按下add group標題時,會變成Group1,Group2等等.. 目前我正在添加一個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
}
uj5u.com熱心網友回復:
也許我錯過了它,但我沒有看到洗掉所有列的代碼,我只看到了一個。但解決方案似乎仍然很簡單,只需groupNum在洗掉 col 時遞減變數
function deleteLastColumn() {
$('#persons tr').find('th:last-child, td:last-child').remove()
groupNum--;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317183.html
標籤:javascript html 查询
上一篇:元素按鈕不能作為后代出現?
下一篇:如何行內一個href?
