2 回答

TA贡献1850条经验 获得超11个赞
I̶t̶'̶s̶ ̶b̶e̶c̶a̶u̶s̶e̶ ̶c̶o̶u̶n̶t̶i̶n̶g̶ ̶f̶o̶r̶ ̶p̶r̶o̶p̶e̶r̶t̶i̶e̶s̶ ̶ ̶a̶n̶d̶ ̶ ̶b̶e̶g̶i̶n̶s̶ ̶f̶r̶o̶m̶ ̶0̶..̶ ̶A̶c̶c̶o̶r̶d̶i̶n̶g̶l̶y̶ ̶f̶o̶r̶ ̶t̶h̶i̶r̶d̶ ̶r̶o̶w̶ ̶a̶n̶d̶ ̶c̶o̶l̶u̶m̶n̶ ̶r̶e̶s̶u̶l̶t̶ ̶w̶i̶l̶l̶ ̶b̶e̶ ̶2̶.̶r̶o̶w̶I̶n̶d̶e̶x̶c̶e̶l̶l̶I̶n̶d̶e̶x̶
更新。
请原谅我的疏忽。调用函数时,方法引用 和 变量,该变量被最后一个循环的迭代覆盖。onclickturnrowcell
如何解决?您需要将变量的初始化和函数设置置于闭包中。rowcellonclick
例如:
cell.onclick = (() => {
// Closure starts here. Now, method turn will be called with variables which was defined down here.
var row = cell.parentElement.rowIndex;
var column = cell.cellIndex;
return () => this.turn(row, column);
})();
在这里,我们创建了自动执行的匿名函数,其中包含和变量的初始化,其中包含所需的值。另外,在这里我们返回了将设置为 onclick 处理程序的函数,并且我们的处理程序包含对已传输变量和 的 turn 调用。rowcellmethodrowcell
因此,每个 onclick 处理程序内部方法调用都传递了在闭包中初始化的 own 和 变量。turnrowcell

TA贡献1796条经验 获得超4个赞
这里需要的是将“唯一”事件侦听器附加到每个单元格。所以,试试这个onclick
cell.addEventListener('click', this.turn.bind(this, row, column))
或
cell.onclick = this.turn.bind(this, row, column);
添加回答
举报