You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于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 setTimeout callbacks
  • The last variable being updated even when clicking non-hidden cards

Problem 2: Can't Hide Matching Card Divs

This issue stemmed from:

  • Shadowing the that variable in your setTimeout callback (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

  1. isProcessingPair Flag: This prevents users from clicking cards while we're waiting for the timeout to hide mismatched pairs, eliminating the "third click" issue.
  2. Variable Scoping Fix: We removed the unnecessary that parameter from setTimeout callbacks and used closure to access the correct card elements.
  3. lastClickedCard Management: Now this variable is only set when we click a valid hidden card, and reset after processing each pair.
  4. Direct Div Hiding: Instead of targeting the image's parent, we directly call hide() on the card divs (lastClickedCard and currentCard), which fixes the hiding issue for matching pairs.
  5. Start Button Integration: Moved the cards variable 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 hidden class (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 17:07:49