我正在制作基本的平铺游戏。单击后,我触发forEach循环以更新当前阵列,然后将其与获胜条件的获胜阵列进行比较。获胜数组是不可变的,当前数组表示带有子节点的父div的innerHTML,如果子节点不存在,则该值为null。
我已经尝试将click处理程序移动到forEach循环中,我尝试使用index参数,并且我尝试在forEach中添加一个新的for循环,如果我可以在单击后获得当前的patten循环。
let winningArrayPattern = ['0', '1', '2', null];`
let currentArrayPattern = [];
const classSquares = document.querySelectorAll('.square');
在NodeList中// children`
const idParents = document.querySelectorAll('.parent');
// NodeList
//我有值,现在将它们映射到父索引
$('.square').click(function () {
currentArrayPattern = [];
idParents.forEach(function(item,index){
if (item.children.length === 1){
console.log(item.children[0].innerHTML, index);`
currentArrayPattern[index]= item.children[0].innerHTML;`
} else {
currentArrayPattern[index] = null;
console.log('parent is empty', index);
}
}); // forEach
console.log(currentArrayPattern, winningArrayPattern);
}); // click`
我被卡住了,最终结果应该是在获胜数组的索引处,对应于该位置的父div中的当前值
答案 0 :(得分:0)
在一些帮助之后,我们发现我在forEach循环之上的click事件处理程序是不正确的。解决方案是删除click事件,在函数中设置块的其余部分,然后在我的jsfile顶部的$(document).ready函数中调用该函数。
我的理解是,当javascript被解析时,它首先读取forEach循环上方的click处理程序,然后当文档准备就绪时,它会看到click事件处理程序。因此,它首先读取第二个,因为DOM还没有完全加载。这是更新的代码:
$('document').ready(function () {
$(' .square')。点击(function(){
const parent = $(this).parent('div');
//console.log(this);
$(this).appendTo('.empty');
$('.empty').addClass('full').removeClass('empty');
parent.addClass('empty').removeClass('full');
checkWin();
}); });