jQuery - Ability to count the number of Rows in a Table?
w jQuery - is it possible to setup a listener that can count the number of rows in a table.
And when the row count changes d开发者_如何学Co X if the count is eq 0 or Y is > 0?
Thanks
One way is to use time listener :
var time = setInterval(function(){
alert( $('#table tr').length );
},1000 );
Or you can put it when the event associated with change num rows executed .
For your first question:
$('table tr').length;
Both .length and .size() will give you the same information. If the table ID is tbl1
, then you use the jQuery CSS selector
$('#tbl1 tr')
If you are using <thead>
, <tbody>
, <tfoot>
properly, then you should use the below to count only the body rows, otherwise take 1 or 2 off the .length
result from the above.
$('#tbl1 tbody tr')
As for observing the row count changes, you need either
- a global var that stores the current row count, coupled with a setInterval event (say 100ms) that checks for changes and raises an event; or
- a class that encapsulates this behaviour with an internal var, but also using setInterval
You could use something like:
$('#tableID').bind('DOMNodeInserted', function() {
var count = $('table tr').length;
alert("The number of rows has changed, there are now " + count + " rows.");
});
JS Fiddle demo.
精彩评论