我一直在尝试使用JavaScript玩井字游戏。在我的过程中,我陷入了addEventListener
部分。我得到了:
未捕获的TypeError:action.addEventListener不是函数
错误。如何解决此问题?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="game.css">
</head>
<body>
<h1>Ultimate Tic Tac Toe</h1>
<h2>Turn: </h2>
<h3><span class="P1">Player 1</span> <span class="P2">Player 2</span></h3>
<div id="grid">
<a href="img/black pic.jpg"></a>
<div class="S1"><img src="img/black pic.jpg"></div>
<div class="S2"><img src="img/black pic.jpg"></div>
<div class="S3"><img src="img/black pic.jpg"></div>
<div class="S4"><img src="img/black pic.jpg"></div>
<div class="S5"><img src="img/black pic.jpg"></div>
<div class="S6"><img src="img/black pic.jpg"></div>
<div class="S7"><img src="img/black pic.jpg"></div>
<div class="S8"><img src="img/black pic.jpg"></div>
<div class="S8"><img src="img/black pic.jpg"></div>
</div>
<script src="game.js"></script>
</body>
</html>
body{
background: url("img/wooden.jpg");
margin: 0;
padding: 0;
}
#grid{
font-size: 0;
width: 800px;
margin: 0 auto;
}
#grid div{
margin: 2px;
border: 4px solid transparent;
display: inline-block;
}
#grid div:hover{
opacity: 0.5;
}
const action = document.querySelectorAll("#grid");
action.forEach(action.addEventListener("click", (e) => {
console.log(e);
}));
答案 0 :(得分:0)
您应该将函数传递给forEach
方法:
使用箭头功能:
action.forEach(action => action.addEventListener("click", (e) => {
console.log(e);
}));