I have an array in which list elements get pushes when I click on them. After 2 elements are inside of it I need a way to check them against each other and see if they are exactly the same. I've tried the basic if(array[0] === array[1])
but that simply returns true (they match) no matter if array[0] = li.whatever
and array[1] = li.notTheSame
.
var $card1 = $clicked[0];
var $card2 = $clicked[1];
function checkMatch(){
if ($clicked.length === 2){
if ($card1 === $card2){
matched();
}else {
$clicked.length = 0;
$('.card').removeClass('open show');
console.log('NOT A MATCH!')
};
}else{
};
};
You seem you just want to compare two values. So, I've made a really basic function basing on what you explained on your code. Is this right one for you?
var div = document.querySelector('div'); var cards = []; div.addEventListener('click', function(e){ e.stopPropagation(); e.target.style.background = 'green'; cards.push(e.target.textContent); checkMatch(); }); function checkMatch(){ if(cards.length <= 1){ return; } if(cards[0] === cards[1]){ alert('Same'); }else{ alert('Different'); } }
div{ width:500px; } li{ width: 100px; height: 100px; background: #E7F3F7; list-style-type:none; text-align: center; display:inline-block; margin:10px; }
<div> <li>Cat</li> <li>Cow</li> <li>Bird</li> <li>Bird</li> <li>Dog</li> <li>Cat</li> <li>Dog</li> <li>Cow</li> </div>
I found the answer from another question I posted. Basically:
let firstCard = array[0];
let secondCard = array[1];
And I changed the "if" that checks the cards to this:
if(firstCard.children().attr('class') === secondCard.children().attr('class')){
"Do something"
}
And it works perfectly. It doesn't find them all as a match anymore!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.