0

私は単純な記憶ゲームを作成していますが、ほとんどすべての作業が完了しています。ただし、ボタンでさまざまな困難を設定できるようにしたかったのですが、ボタンのクリック時に関数を呼び出してテーブルを生成すると、残りのコードが無効になります。これは私のコードです。「#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);
});
4

3 に答える 3

0

$('table').empty(); への呼び出し 表のセルと関連するイベント ハンドラーを破棄します。td のクリック ハンドラーを再バインドするか、次のようなイベント委任を使用する必要があります。

$('table').on('click', 'td', function() {
    //your code here

});

于 2013-06-26T22:17:13.843 に答える