我在 javascript 中有一个代码,我需要替换 tbody 中的内容,除了具有模板类的 tr。我试过了
$('#table').find('tbody').not(".template").html('<tr class="text-center"><td colspan="5">No Todo data</td></tr>');
但它仍然替换了整个 tbody 并且没有将 tr 保留为一类模板。
这是html
<table class="table" id="todo_list">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">ID</th>
<th scope="col">Name</th>
<th scope="col">Todo</th>
<th scope="col" style="width:20%">Action</th>
</tr>
</thead>
<tbody>
<tr class="template" hidden>
<td class="cell"></td>
<td class="cell"></td>
<td class="cell"></td>
<td class="cell"></td>
<td class="cell text-center">
<button class="btn btn-warning btnUpdate" id="btnUpdate">Update</button>
<button class="btn btn-danger btnDelete" id="btnDel">Delete</button>
</td>
</tr>
</tbody>
</table>
最佳答案
您的代码非常接近;需要进行的主要更改是:
- 通过添加
.find("tr")
选择 tbody 的 tr 元素(见下文) - 使用
.replaceWith()
而不是.html()
修改后的方法可以理解为:
$('#table') /* <- select element with id table and then */
.find('tbody') /* <- select the tbody of that table and then */
.find('tr') /* <- select the tr elements of that tbody and then */
.not('.template') /* <- filter tr elements that are not .template and then */
.replaceWith($('<tr class="text-center"><td colspan="5">No Todo data</td></tr>')); /* <- replace those resulting tr elements with new tr */
下面是更新后的代码示例:
$('#table')
.find('tbody')
.find('tr')
.not('.template')
.replaceWith($('<tr class="text-center"><td colspan="5">No Todo data</td></tr>'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="table">
<tbody>
<tr>
<td>Replace me</td>
</tr>
<tr class="template" hidden>
<td class="cell"></td>
<td class="cell"></td>
<td class="cell"></td>
<td class="cell"></td>
<td class="cell text-center">
<button class="btn btn-warning btnUpdate" id="btnUpdate">Update</button>
<button class="btn btn-danger btnDelete" id="btnDel">Delete</button>
</td>
</tr>
<tr>
<td>Replace me</td>
</tr>
</tbody>
</table>
作为最后的说明,一个更简洁的版本可以实现与上面所示相同的结果:
$('tbody tr:not(.template)', '#table')
.replaceWith($('<tr class="text-center"><td colspan="5">No Todo data</td></tr>'));
更新
要将所有不具有 .template
类的行替换为显示为“No todo data”的单个行,您可以执行以下操作:
var nonTemplateRows = $('tbody :not(.template)', '#table');
if(nonTemplateRows.length > 0) {
nonTemplateRows
.empty()
.append($('<tr class="text-center"><td colspan="5">No Todo data</td></tr>'));
}
关于javascript - 替换 tbody 中的内容,除了一个 tr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57655960/