2016-12-16 24 views
-1

我正在製作一個基本的拼圖遊戲。點擊後,我觸發一個forEach循環來更新當前數組,然後將其與勝利條件的獲勝數組進行比較。獲勝數組是不可變的,當前數組表示父子div的子元素的innerHTML,如果子元素不存在,則值爲null。我如何登錄陣列的當前狀態點擊evevt

我試過將點擊處理程序移動到forEach循環中,我嘗試過使用索引參數,並且我嘗試了將一個新的for循環ouside forEach添加到如果我可以在點擊之後獲取當前的模式和循環。

let winningArrayPattern = ['0', '1', '2', null];` 
let currentArrayPattern = []; 

const classSquares = document.querySelectorAll('.square'); 

// children`in的NodeList

const idParents = document.querySelectorAll('.parent'); //節點列表

//我有值,現在把它們映射到父指標

$('.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的當前值

jsfiddle

codepen

回答

0

一些幫助後,我們發現,我不得不foreach循環以上的單擊事件處理程序是不正確的。解決方法是刪除該事件,在函數中設置塊的其餘部分,然後在我的jsfile頂部的$(document).ready函數中調用該函數。

我的理解是,當javascript被解析時,它首先讀取forEach循環上方的click處理程序,然後當文檔準備就緒時,它會看到單擊事件處理程序。所以,它首先閱讀第二個,因爲DOM尚未完全加載。以下是更新後的代碼:

jsFiddle

$('document').ready(function() { 

$點擊(函數(){

const parent = $(this).parent('div'); 
//console.log(this); 
$(this).appendTo('.empty'); 
$('.empty').addClass('full').removeClass('empty'); 
parent.addClass('empty').removeClass('full'); 
checkWin(); 

});( '方')。 });