jQuery:检测表中是否没有行

jQuery:检测表中是否没有行,jquery,Jquery,我试图检测表中是否还有行,一旦没有行,我将显示一个警报。下面的代码似乎不起作用,有什么想法吗?(剩下一行是表头,这就是我使用索引1的原因) 编辑:我尝试在警报之前删除,每次删除一行时它都会触发 再次编辑:得到它,需要创建索引2,因为它在从DOM中实际删除最后一个索引之前进行检查 if ( $(this).closest("tbody").find("tr").length === 0 ) { alert("no rows left"); } 这将查找所单击元素的最接近父级的tbody

我试图检测表中是否还有行,一旦没有行,我将显示一个警报。下面的代码似乎不起作用,有什么想法吗?(剩下一行是表头,这就是我使用索引1的原因)

编辑:我尝试在警报之前删除,每次删除一行时它都会触发


再次编辑:得到它,需要创建索引2,因为它在从DOM中实际删除最后一个索引之前进行检查

if ( $(this).closest("tbody").find("tr").length === 0 ) {
    alert("no rows left");
}

这将查找所单击元素的最接近父级的
tbody
(DOM中始终存在
tbody
)。它检查所述
tbody
tr
元素的长度。如果它等于0,它将显示警报。

如果使用的jQuery早于1.7,则使用
.on()
(或
.delegate()
)而不是
.live()
):

这将使用表作为根元素,而不是
文档
元素。这还假设当此代码运行时,该表将位于DOM中

ya的一些文档:

  • .on()
  • .delegate()
  • .live()
    :(注意顶部关于
    .live()
    折旧的注释)

HTML代码用于上下文。始终使用
=
0
if ( $(this).closest("tbody").find("tr").length === 0 ) {
    alert("no rows left");
}
//bind to the `click` event for all `.remove_row` elements that are in the DOM or will be in the future that have the ancestor `#table-id` element
$('#table-id').on('click', '.remove_row', function () {

    var $TRs = $(this).parents('table:first').find('tr');

    //find the number of rows in the table in which the clicked `.remove_row` element is located
    if ( $TRs.length < 2) {

        alert("no rows left");

    } else {

        $TRs.eq(0).fadeOut(500, function () {

            $(this).remove();

        });

    }

});
$('#table-id').delegate('.remove_row', 'click', function () {