如何使用.addEventListener打印出数组的特定项目?

时间:2019-06-20 18:57:24

标签: javascript arrays addeventlistener

我正在创建一种井字游戏。我有一个用.html映射的网格,我试图让每个框在按下时都说“您单击了'框位置'”。

元素ID的标签为0-8。

let grid =['topLeft','topMid','topRight','midLeft','midMid','midRight','botLeft','botMid','botRight'];

var clickFunction = function() {

    console.log("You Clicked " + grid[i]);  
};

for(i=0; i<grid.length; i++) {
    grid[i] = document.getElementById(i);
    grid[i].addEventListener("click", clickFunction);
}

它当前打印出“您单击未定义”。例如,如何打印“您单击了topLeft”?

2 个答案:

答案 0 :(得分:0)

将索引传递到clickFunction

var clickFunction = function(i) {

console.log("You Clicked " + grid[i]);  
};

for(i=0; i<grid.length; i++) {
  grid[i] = document.getElementById(i);
  grid[i].addEventListener("click", () => clickFunction(i));
}

答案 1 :(得分:0)

第一个:更改此行:

grid[i] = document.getElementById(i);

收件人:

ele = document.getElementById(grid[i]);

由于您需要为处理程序中的每个元素保存i值,因此可以将处理程序更改为:

var clickFunction = function(i) {
    return function(e) {
       console.log("You Clicked " + grid[i]);
    }
};

通过这种方式,当您附加处理程序(... clickFunction(i))时,将保存变量的值。

let grid =['topLeft','topMid','topRight','midLeft','midMid','midRight','botLeft','botMid','botRight'];

var clickFunction = function(i) {
    return function(e) {

        console.log("You Clicked " + grid[i]);
    }
};

for(i=0; i<grid.length; i++) {
    ele = document.getElementById(grid[i]);
    ele.addEventListener("click", clickFunction(i));
}
<button id="topLeft">topLeft</button>
<button id="topMid">topMid</button>
<button id="topRight">topRight</button>
<button id="midLeft">midLeft</button>
<button id="midMid">midMid</button>
<button id="midRight">midRight</button>
<button id="botLeft">botLeft</button>
<button id="botMid">botMid</button>
<button id="botRight">botRight</button>