gpt4 book ai didi

javascript - 如何在 JavaScript 中修复 "Uncaught TypeError: action.addEventListener is not a function"

转载 作者:行者123 更新时间:2023-11-27 23:31:34 25 4
gpt4 key购买 nike

我一直在尝试使用 JavaScript 开发井字游戏。在我的过程中,我卡在了 addEventListener 部分。我得到:

Uncaught TypeError: action.addEventListener is not a function

错误。我该如何解决这个问题?

<!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);
}));

最佳答案

您应该将一个函数传递给 forEach 方法:

使用箭头函数:

action.forEach(action => action.addEventListener("click", (e) => {
console.log(e);
}));

关于javascript - 如何在 JavaScript 中修复 "Uncaught TypeError: action.addEventListener is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57470150/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com