Javascript 如何通过索引选择表单元格?

Javascript 如何通过索引选择表单元格?,javascript,html,Javascript,Html,我知道有一种方法可以访问顺序元素,但我不确定如何通过索引访问它们。有办法吗 我要找的东西是: document.getElementById('table1').cell[1] 要通过行索引和该行内的单元格索引访问单元格,可以使用: var rowIndex = 0; var cellIndex = 1; document.getElementById('table1').rows[rowIndex].cells[cellIndex]; 这将访问第一行(索引0)中的第二个单元格(索引1) 如

我知道有一种方法可以访问顺序元素,但我不确定如何通过索引访问它们。有办法吗

我要找的东西是:

document.getElementById('table1').cell[1]

要通过行索引和该行内的单元格索引访问单元格,可以使用:

var rowIndex = 0;
var cellIndex = 1;
document.getElementById('table1').rows[rowIndex].cells[cellIndex];
这将访问第一行(索引0)中的第二个单元格(索引1)

如果只想使用单元索引(而不跟踪行)并让它遍历每行中的单元,则可以这样做,但前提是每行的单元数相同。下面的代码将访问表中的第四个单元格(索引3),无论它位于第0行、第1行还是第3行;只要每行有相同数量的单元格:

var cellIndex = 3;
var table = document.getElementById('table1');
var num_columns = table.rows[0].cells.length;
var cell = table.rows[Math.floor(cellIndex/num_columns)].cells[cellIndex % num_columns];

要将按id查询限制为元素的树,可以使用
querySelector

document.getElementById('table1').querySelector('#cell1');
但这只是多余的,当你可以简单地做

document.getElementById('cell1');
编辑:为了更好地响应OP的请求,可以通过以下方式顺序访问表格的单元格:

document.getElementById('table1').tBodies[i].rows[j].cells[k];
这将选择表体第
i
-th行的第
j
-th行的第
k
-th单元格。 如果您的表只有一个
元素(像往常一样),或者您希望独立于单元格的
访问单元格,则可以省略
.tBodies[i]
部分。

单元格一个id:

<td id="mycell">
 

表的提供了对行的访问。行的
.cells
集合提供对该行单元格的访问。两者都使用基于零的索引,并具有
.length
属性。因此:

var table = document.getElementById('table1');

alert(table.rows.length);                // number of rows
alert(table.rows[2].cells.length);       // number of cells in row 3

alert(table.rows[2].cells[5].innerHTML); // contents of 6th cell in 3rd row

对不起,我可能说得不够清楚。我想做的是按id选择一个表,然后按顺序编号访问表中的单元格元素(单元格未分配id)啊,你的意思是通过它们的
索引访问它们。啊索引是我要查找的术语,这很有帮助!:]
document.getElementById('table1')。行[0]。单元格[0]
由于子选择器,您将获得零结果。删除它,您将获得所有表中的所有
td
元素,而不仅仅是所需的元素。看起来不错+我选择所有的
td
是错误的。我以为你用的是
qSA
。@Derek,如果相关的话,我是用一个!用它来补充你的答案。哦,+1;)我不明白。你是否也在尝试让它在IE8中工作?因为第三条语句在IE8中不起作用。第一行缺少开括号。很好的解决方案,转到IE8?(+'d this)@Zuul-它至少可以追溯到IE 5(我记不起比这更久远的了)。请修改你的代码getElementByid,我认为应该是getElementByid“I”,大写JS区分大小写:-)
document.querySelector('table td'); //Done. IE8 and above supported.
                                    //Only the first one will be selected.
document.querySelector('#table1 td'); //First cell in #table1

document.querySelector('#table1 td:nth-child(3)'); //Third cell in #table1
document.querySelectorAll('#table1 td')[2];        //or this
var table = document.getElementById('table1');

alert(table.rows.length);                // number of rows
alert(table.rows[2].cells.length);       // number of cells in row 3

alert(table.rows[2].cells[5].innerHTML); // contents of 6th cell in 3rd row