I'm creating a simple memory matching game and I want to compare the text-value of each clicked cell to see if a match is made. The click event handler at the bottom is my attempt to do so but I'm not sure how to save which cell was clicked. How do I save the text-value of each cell and compare them, while also saving which cell I'm comparing so I can hide it if the two cells that were clicked are not equal? Text-indent is set to 100%, and overflow is hidden by default.
var createTable = function (col, row) {
$('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(4, 1);
var arr = [1, 2, 1, 2];
var pushNum = function () {
var len = arr.length;
for (var i = 0; i <= len; i++) {
var ran = Math.ceil(Math.random() * arr.length) - 1;
$('td').eq(i).append(arr[ran]);
arr.splice(ran, 1);
}
};
pushNum();
var match1;
$('td').click(function () {
$(this).css('text-indent', 0);
match1 = $(this).eq();
if (match1.val() === "1") {
alert("GOOD");
}
});
Personally, I think I would create a couple of functions to handle two things:
1) an onclick
function on each cell that would simply toggle some kind of "clicked" class (using toggleClass()
), when a cell is clicked. It could have a visual indicator as well (e.g., change text or background color or something like that).
2) an independent function that would get called by the "onclick" in #1, after the toggle was complete, to check to see if exactly 2 cells had been clicked. you could use a jQuery selector to get all of the cells with the "clicked" class and, if the length of the return set equals 2, then use the first()
and last()
functions to get the values of the clicked cells so that you can compare them. This is the function where you would integrate your existing "do they match" JS code from above.
That way, you wouldn't actually have to store the value, you just wouldn't ever check unless you know that you had two selections made and then you would check them real-time.