2 回答

TA貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個(gè)贊
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?
更新。
請(qǐng)?jiān)徫业氖韬?。調(diào)用函數(shù)時(shí),方法引用 和 變量,該變量被最后一個(gè)循環(huán)的迭代覆蓋。onclickturnrowcell
如何解決?您需要將變量的初始化和函數(shù)設(shè)置置于閉包中。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);
})();
在這里,我們創(chuàng)建了自動(dòng)執(zhí)行的匿名函數(shù),其中包含和變量的初始化,其中包含所需的值。另外,在這里我們返回了將設(shè)置為 onclick 處理程序的函數(shù),并且我們的處理程序包含對(duì)已傳輸變量和 的 turn 調(diào)用。rowcellmethodrowcell
因此,每個(gè) onclick 處理程序內(nèi)部方法調(diào)用都傳遞了在閉包中初始化的 own 和 變量。turnrowcell

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊
這里需要的是將“唯一”事件偵聽(tīng)器附加到每個(gè)單元格。所以,試試這個(gè)onclick
cell.addEventListener('click', this.turn.bind(this, row, column))
或
cell.onclick = this.turn.bind(this, row, column);
添加回答
舉報(bào)