(Vanilla JS) 使用已知索引值触发点击 table 单元格

(Vanilla JS) Triggering click on a table cell using known index values

我正在为 table 制作键盘导航,当我 运行 以下代码时出现此错误:

var newActiveCell = table.rows[activeRowIndex].cells[activeColumnIndex];
newActiveCell.click();

错误:

TypeError: undefined is not an object (evaluating 'table.rows[activeRowIndex].cells')

如果我随后执行 activeCell = document.activeElement,它可以与 .focus() 一起使用,但我想知道是否有更好的方法来编写整个概念。

我没有在 post 中包括变量声明和处理键盘输入以保存 space 的函数,但基本上我想做的是触发点击我有索引值的单元格。

这为我修复了未定义的错误,我之前定义的行和列索引,只要有按键,我就会根据需要增加它们。

var newActiveCell = table.rows[activeRowIndex].cells[activeColumnIndex].focus();
activeCell = document.activeElement;

console.log(activeCell);