我想基本上检测每张卡上的单击事件并将此卡保存在变量中,但firstGuess遮盖了secondGuess。有什么解决方案?
for (let i = 0; i < cards.length; i++) {
//ADDING FLIP EFFECT TO EACH CARD
toggleFlipEffect(cards[i]);
cards[i].addEventListener("click", compareCards, false);
}
function compareCards() {
let points = 0;
let tries = 0;
const firstGuess = this.getElementsByTagName("img")[0].alt;
const secondGuess = this.getElementsByTagName("img")[0].alt;
console.log(firstGuess);
console.log(secondGuess);
if (firstGuess === secondGuess) {
points += 1;
console.log(points);
} else {
firstGuess.classList.remove("card--flip");
secondGuess.classList.remove("card--flip");
}
}
}
最佳答案
没有用于toggleFlipEffect的HTML和代码,就无法知道如何实现卡片翻转。从本质上讲,您需要对第一张卡进行不同的操作,而不是对第二张卡进行单击。首先,您实际上只需要注意它是哪张卡。仅当是第二次时,才需要执行比较。
请注意,如果猜错了,您将需要稍稍延迟才能再次隐藏这些卡,否则用户将没有时间查看第二张卡。
这是您可以执行的操作:
function toggleFlipEffect() {} // mock-up.
var cards = document.querySelectorAll('div');
for (let i = 0; i < cards.length; i++) {
//ADDING FLIP EFFECT TO EACH CARD
toggleFlipEffect(cards[i]);
// *** add data attribute for quicker access
cards[i].dataset.value = cards[i].getElementsByTagName("img")[0].alt;
cards[i].addEventListener("click", compareCards, false);
}
// Your variables should not be local to the click event handler:
let points = 0;
let tries = 0;
let revealed = [];
function compareCards() {
// do not allow more than 2 cards to be revealed in one turn
if (revealed.length >= 2) return;
// reveal clicked card
this.classList.add("card--flip");
// add it to array with the previous one (if there was one)
revealed.push(this);
// Need another card?
if (revealed.length < 2) return; // allow for second choice
// We have two revealed cards. Check if they are the same
if (revealed[0].dataset.value === revealed[1].dataset.value) {
points += 1; // Yes, keep score
revealed = []; // initialise for next turn
score.textContent = points;
} else {
// Different: conceal these two cards again, but after a delay
setTimeout(_ => {
revealed.forEach(elem => elem.classList.remove("card--flip"))
revealed = []; // initialise for next turn
}, 1000);
}
}
.card--flip {
background-color: white;
}
div {
background-color: black;
margin: 5px;
width: 50px;
height: 50px;
display: inline-block;
}
<div><img src="https://image.flaticon.com/icons/svg/418/418278.svg" alt=1></div>
<div><img src="https://image.flaticon.com/icons/svg/418/418268.svg" alt=2></div>
<div><img src="https://image.flaticon.com/icons/svg/418/418275.svg" alt=3></div><br>
<div><img src="https://image.flaticon.com/icons/svg/418/418268.svg" alt=2></div>
<div><img src="https://image.flaticon.com/icons/svg/418/418278.svg" alt=1></div>
<div><img src="https://image.flaticon.com/icons/svg/418/418275.svg" alt=3></div><br>
score: <span id="score"></span>
关于javascript - 如何在点击javascript时检测每个“this”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43950912/