Javascript记忆卡游戏最后一张卡没有翻转

时间:2017-11-04 04:03:39

标签: javascript

嗨我有一个记忆游戏,这里有一个演示。

https://kuochye.github.io/memorygame/

我有一个问题,最后一张卡没有翻过来,也无法找出原因。

document.querySelectorAll(".flip-container").forEach(card => card.classList.add("clicked"));
setTimeout(function () {
document.querySelectorAll(".flip-container").forEach(card => 
card.classList.remove("clicked"));
}, 30000);

^这就是我在卡片向下翻转前30秒显示卡片所做的事情。但不知何故,最后一张卡片没有显示出来。

  // Build single card
 var buildCardNode = function (index, value, isRevealed, width, height) {
var flipContainer = document.createElement("li");
var flipper = document.createElement("div");
var front = document.createElement("a");
var back = document.createElement("a");

flipContainer.index = index;
flipContainer.style.width = width;
flipContainer.style.height = height;
flipContainer.classList.add("flip-container");
if (isRevealed) {
  flipContainer.classList.add("clicked");
}

flipper.classList.add("flipper");
front.classList.add("front");
front.setAttribute("href", "#");
back.classList.add("back");
back.classList.add("card-" + value);
back.setAttribute("href", "#");

flipper.appendChild(front);
flipper.appendChild(back);
flipContainer.appendChild(flipper);

flipContainer.addEventListener('click', handleFlipCard);

  document.querySelectorAll(".flip-container").forEach(card => card.classList.add("clicked"));
setTimeout(function () {
document.querySelectorAll(".flip-container").forEach(card => 
card.classList.remove("clicked"));
}, 30000);

return flipContainer;

 };

1 个答案:

答案 0 :(得分:1)

您正在做的是查找已添加并翻转的每张卡片。这没关系,但是在将每张卡添加到文档之前,您已经这样做了。因此,对于添加的每张卡,它会找到之前添加的每张卡并将其翻转。

你想做两件事之一:

一个。将所有卡添加到文档后将其翻转(通过将第一段代码从buildCardNode函数移动到调用它的位置)。

湾在将每张卡添加到文档之前直接翻转(而不是使用document.querySelectorAll.forEach,使用flipContainer.classList.add / remove)。

相关问题