4 回答

TA貢獻1820條經驗 獲得超2個贊
只需將您的 th 更新為 thead 就可以了,請參見下文:
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
</head>
<body onLoad="delTable()">
<table id="TableA">
<thead>
<tr>
<td>Col A</td>
<td>Col B</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
</body>
</html>
JS:
function delTable() {
console.log("Delete all rows, but the header");
// Option-A
// $('#TableA tbody tr').remove();
// Option-B
// Accepted answer for: https://stackoverflow.com/questions/9420203/how-to-remove-all-rows-of-the-table-but-keep-the-header
// $('#TableA tr').not(function(){ return !!$(this).has('th').length; }).remove();
// Option-C
$('#TableA tbody').empty();
}
工作小提琴: https ://jsfiddle.net/pvfkxdby/1/

TA貢獻1772條經驗 獲得超6個贊
這對我有用。<th>你用而不是分開你的標題,<thead>然后你<td>在你的標題中而不是<th>。
$(document).ready(() => {
$("#delete").click(() => {
$("#TableA tbody tr").remove()
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="TableA">
<thead>
<tr>
<th>Col A</th>
<th>Col B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
<button id="delete">delete</button>

TA貢獻2019條經驗 獲得超9個贊
通過在我的 Google Chrome 中檢查您的 HTML,我可以看到行已重新排列,因此即使第一行也在<tbody>
標簽內。因此整個表被刪除。您可以簡單地通過將第一行包裝在<thead>
標簽中或使用不使用<tbody>
標簽的不同方法來解決此問題。

TA貢獻1942條經驗 獲得超3個贊
您需要替換th為thead并使用$('#TableA tbody').find("tr")如下:
function delTable() {
console.log("Delete all rows, but the header");
$('#TableA tbody').find("tr").remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body onLoad="delTable();">
<table id="TableA">
<thead>
<tr>
<td>Col A</td>
<td>Col B</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
</body>
</html>
添加回答
舉報