基于jQuery的记忆游戏元素隐藏问题技术求助
Fixing Your jQuery Memory Game Issues
Let's walk through the two problems you're facing and fix them step by step.
Problem 1: Third Click Doesn't Hide Previous Cards
The root causes here are:
- No guard to prevent clicks while we're waiting for the timeout to finish (leading to unexpected behavior when clicking during that window)
- Incorrect variable scoping in your
setTimeoutcallbacks - The
lastvariable being updated even when clicking non-hidden cards
Problem 2: Can't Hide Matching Card Divs
This issue stemmed from:
- Shadowing the
thatvariable in yoursetTimeoutcallback (passing it as a parameter made the callback use the wrong value) - Not directly referencing the div elements when attempting to hide them
Corrected JavaScript Code
Here's the fixed code with comments explaining each key change:
// Initialize game state variables let cards; let amountClicked = 0; let clicks = 0; let lastClickedCard = null; let isProcessingPair = false; // Prevents overlapping clicks // Start button handler (add this if you don't have it already) $("#start").click(function() { // Get selected board size when start is clicked cards = parseInt($("input:radio[name='size']:checked").val()); // Clear existing cards from the field $("#memoryField").empty(); // Reset all game state variables amountClicked = 0; clicks = 0; lastClickedCard = null; isProcessingPair = false; // Add your card generation logic here (shuffled pairs of images) // Example loop to create cards: // for (let i = 0; i < cards; i++) { // $("#memoryField").append(`<div><img src="your-image-path.jpg" class="hidden"></div>`); // } }); // Card click handler $("#memoryField div").click(function () { // Ignore clicks if we're processing a pair or the card is already visible/matched if (isProcessingPair || !$("img", this).hasClass("hidden")) { return; } // Show the clicked card $("img", this).removeClass("hidden").addClass("visible"); amountClicked++; clicks++; if (amountClicked === 1) { // Store the first clicked card for comparison lastClickedCard = $(this); } else if (amountClicked === 2) { isProcessingPair = true; // Block further clicks until we finish processing const currentCard = $(this); const lastImg = $("img", lastClickedCard); const currentImg = $("img", currentCard); // Check if the two clicked images match if (lastImg.attr("src") !== currentImg.attr("src")) { // Mismatch: hide both cards after a short delay setTimeout(function () { lastImg.removeClass("visible").addClass("hidden"); currentImg.removeClass("visible").addClass("hidden"); // Reset state for next pair amountClicked = 0; lastClickedCard = null; isProcessingPair = false; // Allow clicks again }, 800); } else { // Match: hide the entire card divs setTimeout(function () { lastClickedCard.hide(); currentCard.hide(); // Reset state for next pair amountClicked = 0; lastClickedCard = null; cards -= 2; isProcessingPair = false; // Allow clicks again // Check if the game is complete if (cards === 0) { alert(`Congratulations! You finished in ${clicks} clicks!`); } }, 500); } } });
Key Changes Explained
isProcessingPairFlag: This prevents users from clicking cards while we're waiting for the timeout to hide mismatched pairs, eliminating the "third click" issue.- Variable Scoping Fix: We removed the unnecessary
thatparameter fromsetTimeoutcallbacks and used closure to access the correct card elements. lastClickedCardManagement: Now this variable is only set when we click a valid hidden card, and reset after processing each pair.- Direct Div Hiding: Instead of targeting the image's parent, we directly call
hide()on the card divs (lastClickedCardandcurrentCard), which fixes the hiding issue for matching pairs. - Start Button Integration: Moved the
cardsvariable assignment inside the start button handler so it updates when the user selects a new board size.
Extra Tips
- Ensure your image elements start with the
hiddenclass (use CSS like.hidden { display: none; }or.hidden { opacity: 0; }to control visibility). - When generating cards, shuffle pairs of identical images to create a proper memory game experience.
- Add hover effects or visual feedback to make the game more intuitive for users.
内容的提问来源于stack exchange,提问作者xyz
相关产品推荐
相关产品推荐

