[英]How to check if there are no elements/tags inside another element/tag with jQuery
我在整个Stack Overflow网站上都进行了搜索,但可以找到答案
当<tbody>
没有<tr>
时,下面的代码不会显示任何警报,这是为什么?
我确定以下方法可以工作,但是什么也没发生:
<script>
$('td > a').click(function(e){
var this_elem = $(this);
if( this_elem.hasClass("remove") ){
this_elem.parent().parent().remove();
}
return false;
});
if( $("tbody > tr").length === 0 ){
alert("No more rows of products...");
}
</script>
HTML:
<table>
<tbody>
<tr>
<td class="first-td">
<img src="assets/product-image.jpg" alt="product image" />
<div class="prod-desc-col">
<h3>Samsung LE40C580J1 LCD HD 1080p Digital Television, 40 Inch with Built-in Freeview HD, Samsung LE40C580J1 LCD HD 1080p Digital Television, 40 Inch with Built-in Freeview HD</h3>
<p>Product Code: 1254782</p>
<p>In stock</p>
</div>
</td>
<td>
<input type="text" value="1" size="4" />
<a href="#" title="Update" class="update">Update</a>
<a href="#" title="Remove" class="remove">Remove</a>
</td>
</tr>
</tbody>
</table>
因为你不计算下一行,您要统计所有行的tbody
中的所有 table
在页面秒。
考虑到添加到该问题的其他详细信息,我向您提供以下内容:
$('a.remove').click(
function() {
$(this).closest('tr').remove(); // a slightly more concise form of your own code
return false;
});
$('table tbody').bind('DOMNodeRemoved', function() {
var c = $('table tbody tr').length;
if (c === 1) { // testing against '1' because the count is performed before
// the row is actually removed from the DOM.
alert("The final row is about to go.");
}
});
JS小提琴演示 。
页面中只有一张桌子吗? 否则,您将计算页面中所有表中的所有行。
要计算行数,您可以在这里查看我的测试: http : //jsfiddle.net/2DDZz/
当您发布代码时,我看到您仅在页面加载时检查行数。 每次删除行时,都应检查它:
$('td > a').click(function(e){
var this_elem = $(this);
if( this_elem.hasClass("remove") ){
this_elem.parent().parent().remove();
if( $("tbody > tr").length === 0 ){
alert("No more rows of products...");
}
}
return false;
});
您没有为我们提供太多信息,但是我的第一个猜测是您的JQuery选择器在页面上的ANY表中查找行。 如果页面中还有其他表,则这些行也可能被计数。 您需要做的是使您的JQuery选择器更加具体。 例如:
if( $(" #myTableName > tbody > tr").length === 0 ){
alert("No more rows of products...");
}
注意,我已经向选择器添加了一个ID。 这告诉JQuery只在表中查找ID为“ myTableName
”的行。
也许您应该考虑使用nextAll
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.