替换正文中除一个 TR 之外的内容



我在javascript中有一个代码,我需要替换tbody中的内容,除了具有模板类的tr。我试过了

$('#table').find('tbody').not(".template").html('<tr class="text-center"><td colspan="5">No Todo data</td></tr>');

但它仍然替换了整个主体,而不是用一类模板保留 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")来选择身体的 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类的所有行替换为读取"无待办事项数据"的单行,您可以执行以下操作:

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>'));
}

你可以尝试这种方式 ->使用模板类获取行的html代码,然后附加到它

$('#table').find('tbody').html(
'<tr>'+
$('#table').find('tbody').find(".template").html()+
'</tr>+
'<tr class="text-center"><td colspan="5">No Todo data</td></tr>');

最新更新