这是我的代码:-
$("span").on('click', function() {
if (confirm("are you sure?")) {
$(this).closest("tr").remove();
} else {
return false;
}
var remained_trs = $(this).closest("table").find("span");
if (remained_trs.length < 1) {
$('body').html('there is not any element');
}
})
span {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>one</td>
<td><span>×</span></td>
</tr>
<tr>
<td>two</td>
<td><span>×</span></td>
</tr>
<tr>
<td>three</td>
<td><span>×</span></td>
</tr>
</table>
如您所见,当我删除一个元素时(还有一些其他元素),但是没有任何元素
出现。为什么?我该如何解决?
最佳答案
当 $(this).closest("tr").remove();
执行时,元素从 DOM 中移除到 this
的范围内,完全丢失。
在删除行之前存储表的引用,然后执行删除操作。
var table = $(this).closest("table");
$("span").on('click', function() {
//Store the reference of table before removing the row.
var table = $(this).closest("table");
if (confirm("are you sure?")) {
$(this).closest("tr").remove();
} else {
return false;
}
var remained_trs = table.find("span");
if (remained_trs.length < 1) {
$('body').html('there is not any element');
}
})
span {
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>one</td>
<td><span>×</span></td>
</tr>
<tr>
<td>two</td>
<td><span>×</span></td>
</tr>
<tr>
<td>three</td>
<td><span>×</span></td>
</tr>
</table>
关于javascript - 如何检查没有元素剩余?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43316195/