我正在创建一个简单的记忆游戏,几乎所有事情都完成了。但是,我希望能够使用按钮设置不同的难度,但是调用我的函数以在按钮单击时生成表格会使其余代码无效。这是我的代码。有人能告诉我为什么单击“#easy、#medium、#hard”按钮之一会使表格单元格无法单击吗?
//Creates all of the variables to be manipulated later
var countCells;
var cardValues = [];
var checker = true;
var tempArr = [];
var winCounter = 0;
//Generates a table with the dimensions specified
var createTable = function (row, col) {
$('table').empty();
for (var i = 1; i <= row; i++) {
$('table').append($('<tr>'));
}
for (var j = 1; j <= col; j++) {
$('tr').append($('<td>'));
}
countCells = row * col;
};
createTable(3, 6);
//Creates a new game with various difficulties
$('#easy').click(function () {
createTable(2, 5);
});
$('#medium').click(function () {
createTable(3, 6);
});
$('#hard').click(function () {
createTable(4, 9);
});
//Adds a number for half of the cells into an array twice
for (var k = 1; k <= countCells / 2; k++) {
cardValues.push(k);
if (k === countCells / 2 && checker) {
checker = false;
k = 0;
}
}
//Adds a random number from the array to each of the cells
var giveCellValue = function () {
var len = cardValues.length;
for (var i = 0; i <= len; i++) {
var random = Math.ceil(Math.random() * cardValues.length) - 1;
$('td').eq(i).append(cardValues[random]);
cardValues.splice(random, 1);
}
};
giveCellValue();
//Checks for matches when cells are clicked
$('td').click(function () {
if ($(this).hasClass('clicked') || $(this).hasClass('completed')) {
$(this).stopPropagation();
$(this).preventDefault();
return;
}
$(this).addClass('clicked');
tempArr.push($(this).text());
var len = tempArr.length;
if (len > 1) {
if (tempArr[0] === tempArr[1]) {
alert("Good job!");
$('.clicked').addClass('completed');
$('.completed').removeClass('clicked');
winCounter = winCounter + 1;
} else {
alert("Try again!");
$('.clicked').removeClass('clicked');
}
tempArr.splice(0, 2);
}
if (winCounter === countCells / 2) {
alert('You won!');
}
console.log(countCells, winCounter);
});