Getting td by index with jQuery
I know how to get a cell's row and column index with jQuery, but I can't figure out the reverse. Given a row and column index, how would I开发者_C百科 access the td at this location?
With plain JavaScript:
// table is a reference to your table
table.rows[rowIndex].cells[columnIndex]
Reference: HTMLTableElement
, HTMLTableRowElement
With jQuery, you could use .eq()
:
$('#table tr').eq(rowIndex).find('td').eq(columnIndex)
// or
$('#table tr:eq(' + rowIndex + ') td:eq(' + columnIndex + ')')
How about using the nth-child
selector?
http://api.jquery.com/nth-child-selector/
var row = 4;
var col = 2
var cell = $('table#tableId tr:nth-child(' + row + ') td:nth-child(' + col + ')');
Note that the child index is 1-based, rather than the more usual 0-based.
You can use the :eq
selector:
var row = 1;
var col = 2;
var cell = $('table tr:eq(' + row + ') td:eq(' + col + ')');
Here's an example of this in action
精彩评论