我正在制作四连环游戏,需要记录被单击的td或表格单元,但是控制台中是否还有其他内容?任何想法如何做到这一点?我正在尝试通过选择所有表格单元格来做到这一点
const cells = document.querySelectorAll('td');
然后向每个单元格添加一个事件
for(let i = 0; i < cells.length; i++) {
//add event listener to each cell
cells[i].addEventListener('click', placeChip(this));
然后函数看起来像这样
function placeChip(cell) {
console.log(cell);
}
const board = document.querySelector('table');
const cells = document.querySelectorAll('td');
//select and darken chosen column
board.addEventListener('mouseover', function(e) {
//determine which column is being hovered over and store in var
let column = e.target.className;
//loop through all table cells
for(let i = 0; i < cells.length; i++) {
//add event listener to each cell
cells[i].addEventListener('click', placeChip(this));
//check to see if table cells class matches column
if(cells[i].className === column) {
//change the background color of the matched cells
cells[i].style.backgroundColor = '#0000cc';
} else {
//change unmatched cells to the default color
cells[i].style.backgroundColor = 'blue';
}
}
})
function placeChip(cell) {
console.log(cell);
}
html, body {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: flex-end;
min-height: 100vh;
background-color: #e6e6e6;
}
table {
background-color: #0000cc;
}
td {
border: 3px solid #0000cc;
width: 100px;
height: 100px;
background-color: blue;
transition: all 0.5s ease;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Connect Four</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="board-wrapper">
<table>
<tr class="row-1">
<td class="column-1"></td>
<td class="column-2"></td>
<td class="column-3"></td>
<td class="column-4"></td>
<td class="column-5"></td>
<td class="column-6"></td>
<td class="column-7"></td>
</tr>
<tr class="row-2">
<td class="column-1"></td>
<td class="column-2"></td>
<td class="column-3"></td>
<td class="column-4"></td>
<td class="column-5"></td>
<td class="column-6"></td>
<td class="column-7"></td>
</tr>
<tr class="row-3">
<td class="column-1"></td>
<td class="column-2"></td>
<td class="column-3"></td>
<td class="column-4"></td>
<td class="column-5"></td>
<td class="column-6"></td>
<td class="column-7"></td>
</tr>
<tr class="row-4">
<td class="column-1"></td>
<td class="column-2"></td>
<td class="column-3"></td>
<td class="column-4"></td>
<td class="column-5"></td>
<td class="column-6"></td>
<td class="column-7"></td>
</tr>
<tr class="row-5">
<td class="column-1"></td>
<td class="column-2"></td>
<td class="column-3"></td>
<td class="column-4"></td>
<td class="column-5"></td>
<td class="column-6"></td>
<td class="column-7"></td>
</tr>
<tr class="row-6">
<td class="column-1"></td>
<td class="column-2"></td>
<td class="column-3"></td>
<td class="column-4"></td>
<td class="column-5"></td>
<td class="column-6"></td>
<td class="column-7"></td>
</tr>
</table>
</div>
<script src="script.js"></script>
</body>
</html>