javascript - 事件侦听器如何指向不同的对象?
问题描述
我正在尝试执行 Odin 项目中的井字游戏任务。
这是我的 JavaScript
const boxes = document.querySelectorAll('.box');
console.log(boxes);
console.log('working');
const board = [
];
for (let i = 0; i<boxes.length; i++) {
const objectBox = {position: i+1,
ownership: 'none'}
board.push(objectBox);
boxes[i].addEventListener("click", function(){
console.log(this);
});
}
这是我的 HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tic Tac Toe</title>
<link rel="stylesheet" href="style.css">
<link href="https://css.gg/css?=|bot|boy" rel="stylesheet">
</head>
<body>
<div id="container">
<h1>Tic Tac Toe</h1>
<div id="board">
<div class="box no-ownership"></div>
<div class="box no-ownership"></div>
<div class="box no-ownership"></div>
<div class="box no-ownership"></div>
<div class="box no-ownership"></div>
<div class="box no-ownership"></div>
<div class="box no-ownership"></div>
<div class="box no-ownership"></div>
<div class="box no-ownership"></div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
所以我有一个数组,其中包含具有正方形所有权等信息的对象。显然 eventlistener 指向 div 所以我无法访问该对象。objectBox[0]
例如,当我点击第一个方块时,我想要访问
我真的无法在网上找到任何信息。
提前致谢。
解决方案
您可以在事件处理程序中引用 objectBox 变量,因为它是在同一范围内定义的。
const objectBox = {position: i+1,
ownership: 'none'}
board.push(objectBox);
boxes[i].addEventListener("click", function(){
console.log(this);
console.log(objectBox.ownership);
});
EDIT2:这通常是不好的做法,最好将 HTML 元素和数据对象映射到自定义变量,或者:“一种更简洁的方法是使用数据属性来存储要与之关联的数据对象的索引元素。” @AdityaParab
除此之外,我相信您可以将 objectBox 变量本身分配给查询的元素,例如: EDIT: commented
for (let i = 0; i<boxes.length; i++) {
//declares variable (allocates memmory and returns "pointer")
const objectBox = {position: i+1,
ownership: 'none'}
board.push(objectBox);
boxes[i].dataObject = objectBox;
boxes[i].addEventListener("click", function(){
console.log(this);
//holds the reference to objectBox regardeless of i value
//the loop creates 9 event handlers and each stores reference to the object created in relevant loop run
console.log(this.dataObject);
});
}
编辑:它如何不起作用
如果您尝试创建 objectBox 变量,然后在两个单独的循环中的 onclick 方法中引用它们...
for (let i = 0; i<boxes.length; i++) {
//declares variable (allocates memmory and returns "pointer")
const objectBox = {position: i+1, ownership: 'none'}
}
for (let i = 0; i<boxes.length; i++) {
boxes[i].addEventListener("click", function(){
//this would assign the LAST objectBox to ALL event handlers, as the objectBox variable would be 9 times overwritten in the previous loop
console.log(this.dataObject);
});
}
推荐阅读
- spring - 附加多个文本框
- powershell - 脚本中的排序状态(powershell)
- sql - 在 postgresql 中解析字符串
- groovy - Maven-surefire 没有运行带有 @Tag 注释的 Spock 测试
- jooq - 如何从 SQL 查询配置 jOOQ 可嵌入类型
- swift - 如何从 alamofire 发布请求中使用 switfyJson 填充 UItableview 中的单元格
- c - 尽管创建了有效的文件描述符,但在使用管道时使用 dup2 失败
- javascript - 使用 Esprima 检测缺少的分号解析 JavaScript
- vue.js - 路由器视图中的 Vue 路由器 addRoute 空白
- xml - 向另一个 API 发送 SOAP 请求?