2011-12-23 23 views
3

我試圖檢測表中是否存在任何行,如果沒有任何行存在,我將顯示警報。下面的代碼似乎不工作,有什麼想法? (將會有一行留下了表頭,這就是爲什麼我使用的索引1)jQuery:檢測表中是否沒有剩餘行

$('.remove_row').live('click', function() { 

    //If there are no rows left in table, display alert 
    if ($(this).parent().parent().parent().children('tr:eq(1)').length == 0) { 

     alert("no rows left"); 

    } 

    $(this).parent().parent().remove(); 

}); 

編輯:我試圖與警報之前刪除,這觸發我每次刪除行的時間。


編輯再次:得到它,需要使索引2,因爲它是檢查之前,最後一個實際上是從DOM中刪除。

+1

HTML代碼請上下文。 – 2011-12-23 21:24:46

+0

請始終使用'==='與'0'進行比較 – 2011-12-23 21:32:02

回答

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

此發現cloest父點擊的元素的tbody(一個tbody總是存在於DOM)。它檢查在tbody內的tr元素的長度。如果它等於0,它將顯示警報。

0

而不是使用.live()的,(如果你使用的是jQuery的年紀比1.7或.delegate())使用.on()

//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(); 

     }); 

    } 

}); 

這裏是一個演示:http://jsfiddle.net/UbUbM/

使用.delegate()事件綁定會是什麼樣子這個:

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

這將使用你的表作爲根元素比document元素。這也假設這個代碼運行時表格將在DOM中。

有些文檔爲雅: