我需要删除从 ID 为“#deleteFirstRow”的行到 ID 为“#deleteLastRow”的行范围内的表行。但是这两个 ID 中的所有其他行都应该保留。 注意:我试图搜索已发布的答案,但没有得到任何有效的解决方案。请帮忙!
这是我的桌子:
<table>
<tr>doNotDeleteRow</tr>
<tr>doNotDeleteRow</tr>
<tr>doNotDeleteRow</tr>
<tr id="deleteFirstRow">deleteRow</tr>
<tr>deleteRow</tr>
<tr>deleteRow</tr>
<tr>deleteRow</tr>
<tr id="deleteLastRow">deleteRow</tr>
<tr>doNotDeleteRow</tr>
<tr>doNotDeleteRow</tr>
<tr>doNotDeleteRow</tr>
</table>
我试过这段代码:
$("table tr:not(#deleteFirstRow, #deleteLastRow)").remove();
但是这段代码删除了除了 ID 为“#deleteFirstRow”和“#deleteLastRow”的行之外的所有行。
我想要的是只删除“#deleteFirstRow”和“#deleteLastRow”之间的行,同时删除“#deleteFirstRow”和“#deleteLastRow”。
所以预期的结果应该如下所示:
<table>
<tr>doNotDeleteRow</tr>
<tr>doNotDeleteRow</tr>
<tr>doNotDeleteRow</tr>
<tr>doNotDeleteRow</tr>
<tr>doNotDeleteRow</tr>
<tr>doNotDeleteRow</tr>
</table>
可以
slice
基于两个边界元素的所有行的集合,然后调用remove
.
const rows = $('table tr');
rows.slice(rows.index($('#deleteFirstRow')),
rows.index($('#deleteLastRow')) + 1).remove();
tr {
display: block;
border: 1px solid;
padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr class="doNotDeleteRow"><td>1</td></tr>
<tr class="doNotDeleteRow"><td>2</td></tr>
<tr class="doNotDeleteRow"><td>3</td></tr>
<tr id="deleteFirstRow"><td>4</td></tr>
<tr class="deleteRow"><td>5</td></tr>
<tr class="deleteRow"><td>6</td></tr>
<tr class="deleteRow"><td>7</td></tr>
<tr id="deleteLastRow"><td>8</td></tr>
<tr class="doNotDeleteRow"><td>9</td></tr>
<tr class="doNotDeleteRow"><td>10</td></tr>
<tr class="doNotDeleteRow"><td>11</td></tr>
</table>
用vanilla js也可以做到
在这里,我们循环遍历行,直到我们命中一行 ID 为“deleteFirstRow”的行,然后我们将删除设置为 true,然后我们删除()每一行,直到我们命中行 ID“deleteLastRow”,然后我们删除该行也是。
const rows = document.querySelectorAll('table tr');
let deleting = false;
for (row of rows) {
if (row.id == 'deleteFirstRow') {
deleting = true;
}
if (row.id == 'deleteLastRow') {
deleting = false;
row.remove();
}
if (deleting) {
row.remove();
}
}
<table>
<tr><td>doNotDeleteRow</td></tr>
<tr><td>doNotDeleteRow</td></tr>
<tr><td>doNotDeleteRow</td></tr>
<tr id="deleteFirstRow"><td>deleteRow</td></tr>
<tr><td>deleteRow</td></tr>
<tr><td>deleteRow</td></tr>
<tr><td>deleteRow</td></tr>
<tr id="deleteLastRow"><td>deleteRow</td></tr>
<tr><td>doNotDeleteRow</td></tr>
<tr><td>doNotDeleteRow</td></tr>
<tr><td>doNotDeleteRow</td></tr>
</table>
编辑:修正错别字