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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:25:00  来源:igfitidea点击:

Getting td by index with jQuery

javascriptjqueryhtmlindexinghtml-table

提问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

参考:HTMLTableElementHTMLTableRowElement



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-childselector?

如何使用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 :eqselector:

您可以使用:eq选择器:

var row = 1;
var col = 2;
var cell = $('table tr:eq(' + row + ') td:eq(' + col + ')');

Here's an example of this in action

这是一个在行动中例子