记忆游戏点击卡片无翻转效果问题排查求助
Hey there! Let's troubleshoot why your memory game cards aren't flipping when clicked. I’ve gone through your code snippets and here are targeted fixes and checks to get things working:
1. Fix Variable Scoping in Your Loop
Right now, you’re using an undeclared card variable in your for loop, which creates a global variable that ends up pointing only to the last card by the time the loop finishes. This breaks event binding for all other cards. Update your loop to declare card with let:
for (let i = 0; i < cards.length; i++) { let card = cards[i]; // Add let here to scope the variable to each loop iteration card.addEventListener('click', displayCard); card.addEventListener('click', cardOpen); card.addEventListener('click', congratulations); }
Or even cleaner, use forEach to avoid index-related scoping issues entirely:
cards.forEach(card => { card.addEventListener('click', displayCard); card.addEventListener('click', cardOpen); card.addEventListener('click', congratulations); });
2. Ensure cards Is Properly Selected
Double-check that your cards variable is actually grabbing the elements you want. If you’re using document.getElementsByClassName('card'), note that this returns an HTMLCollection, not an array—you might need to convert it to an array first with Array.from(cards) before looping. Add console.log(cards) right before your loop to confirm it’s not an empty collection.
3. Verify Function Order
Make sure your displayCard function is defined before you bind the click events. If the function is declared after the loop, the browser won’t recognize it when setting up event listeners, so clicks won’t trigger anything. Rearrange your code like this:
// Define functions first let displayCard = function() { this.classList.toggle('open'); this.classList.toggle('show'); this.classList.toggle('disabled'); }; // Then bind events cards.forEach(card => { card.addEventListener('click', displayCard); // ...other event bindings });
4. Check CSS Specificity & Element Accessibility
Your CSS uses .card-deck .card.open and .card-deck .card.show—these have high specificity, which is good, but make sure:
- The
thiskeyword indisplayCardis actually pointing to the clicked card. Addconsole.log(this)inside the function to confirm it logs the correct<li>element when clicked. - No parent element has
pointer-events: noneor is covering the cards (check forz-indexissues,opacity: 0, orvisibility: hiddenon parent containers).
5. Test a Minimal Working Example
If you’re still stuck, try stripping down the code to a minimal version: create a single card, bind only the displayCard function, and see if toggling the classes works. This will help you isolate whether the issue is with event binding, CSS, or another part of your code.
Give these steps a try—chances are one of them will get your cards flipping again!
内容的提问来源于stack exchange,提问作者nCardot

