Javascript 使用 jQuery 通过索引获取 td
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6139407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting td by index with jQuery
提问by Felix Kling
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 access the td at this location?
我知道如何使用 jQuery 获取单元格的行和列索引,但我无法弄清楚相反的情况。给定行和列索引,我将如何访问此位置的 td?
回答by Felix Kling
With plain JavaScript:
使用纯 JavaScript:
// table is a reference to your table
table.rows[rowIndex].cells[columnIndex]
Reference:HTMLTableElement
, HTMLTableRowElement
参考:HTMLTableElement
,HTMLTableRowElement
With jQuery, you could use .eq()
:
使用 jQuery,您可以使用.eq()
:
$('#table tr').eq(rowIndex).find('td').eq(columnIndex)
// or
$('#table tr:eq(' + rowIndex + ') td:eq(' + columnIndex + ')')
回答by Richard Ev
How about using the nth-child
selector?
如何使用nth-child
选择器?
http://api.jquery.com/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.
请注意,子索引是基于 1 的,而不是更常见的基于 0 的索引。
回答by Rob
You can use the :eq
selector:
您可以使用:eq
选择器:
var row = 1;
var col = 2;
var cell = $('table tr:eq(' + row + ') td:eq(' + col + ')');
Here's an example of this in action