所以,我有一个记忆游戏,我必须添加逻辑,当点击两张牌时它们匹配,你只能一次翻转两张牌。所以我必须找到一种跟踪两张翻转牌的方法,任何人都有任何想法我怎么能这样做?我尝试了一个数组,但从未成功,也有两个变量但从未工作过。 这是我的JS:
//declare variables
const deck = document.querySelector(".deck");
cp card = document.querySelectorAll(".card");
let cards = [];
// function to convert a nodelist to array from https://stackoverflow.com/questions/3199588/fastest-way-to-convert-javascript-nodelist-to-array
for(var i = card.length; i--; cards.unshift(card[i]));
console.log(cards);
//add event listener for each card
for(var i = 0; i< card.length;i++){
card[i].addEventListener("click", function(){
this.classList.toggle("open");
this.classList.toggle("show");
});
};
//Call the startGame function to start the game and shuffle cards
window.onload = startGame();
// Shuffle function from http://stackoverflow.com/a/2450976
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
//shuffle cards
function startGame() {
shuffle(cards).forEach(function(item) {
deck.appendChild(item);
});
}
html是16个div,有16个卡和8个符号,2个卡共享一个符号
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Matching Game</title>
<meta name="description" content="">
<link rel="stylesheet prefetch" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css">
<link rel="stylesheet prefetch" href="https://fonts.googleapis.com/css?family=Coda">
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<div class="container">
<header>
<h1>Matching Game</h1>
</header>
<section class="score-panel">
<ul class="stars">
<li><i class="fa fa-star"></i></li>
<li><i class="fa fa-star"></i></li>
<li><i class="fa fa-star"></i></li>
</ul>
<span class="moves"></span> Moves
<div class="restart">
<i class="fa fa-repeat"></i>
</div>
</section>
<ul class="deck">
<li class="card">
<i class="fa fa-diamond"></i>
</li>
<li class="card">
<i class="fa fa-paper-plane-o"></i>
</li>
<li class="card">
<i class="fa fa-anchor"></i>
</li>
<li class="card">
<i class="fa fa-bolt"></i>
</li>
<li class="card">
<i class="fa fa-cube"></i>
</li>
<li class="card">
<i class="fa fa-anchor"></i>
</li>
<li class="card">
<i class="fa fa-leaf"></i>
</li>
<li class="card">
<i class="fa fa-bicycle"></i>
</li>
<li class="card">
<i class="fa fa-diamond"></i>
</li>
<li class="card">
<i class="fa fa-bomb"></i>
</li>
<li class="card">
<i class="fa fa-leaf"></i>
</li>
<li class="card">
<i class="fa fa-bomb"></i>
</li>
<li class="card">
<i class="fa fa-bolt"></i>
</li>
<li class="card">
<i class="fa fa-bicycle"></i>
</li>
<li class="card">
<i class="fa fa-paper-plane-o"></i>
</li>
<li class="card">
<i class="fa fa-cube"></i>
</li>
</ul>
</div>
<script src="js/app.js"></script>
</body>
</html>