简体   繁体   中英

compare data attributes in JS

I have memory card game, i want to make a button that find a pair card of the first selected.

i have HTML like this:

<div class="card" data-card="1" >
<div class="card" data-card="7" >
<div class="card" data-card="5" >
<div class="card" data-card="1" >
<div class="card" data-card="7" >
<div class="card" data-card="5" >

Twice ( for two card that are the same). This is what my JavaScript function of the button look like:

function findPair(){
let divsCards = document.querySelectorAll('.card');

for (i = 0; i < divsCards.length; i++){

Array.from(divsCards).forEach(function(card){
    if(card.dataset.card === card.dataset.card){
        divsCards[i].classList.add('flipped');
    }
});
   }
    }

I know that my statment is'nt good, What i'm trying to compare is the "data-card" value, So if the i click on card with value 5 for example, I want the other 5 value card to be "flipped" when i click the find pair button, but i tried anything i know . I'm really beginner to JS.

Without knowing more about your desired result, it is hard to answer this question, but I am going to assume that the player has flipped over a card and you want to find that matching card in the array of cards. Here is what I would do...

First, add a unique identifier to each card element so that you don't match a pair off of the same card instance:

<div class="card" data-card="1" data-uid="100">
<div class="card" data-card="7" data-uid="101">
<div class="card" data-card="5" data-uid="102">

Note that I just chose to start the uid values at 100 so they are easy to tell apart from the card values.

Then, when a user flips over a card, you would pass the card value and uid to the findPair() method so that you can find the match like so:

function findPair(card, uid) {
    let divsCards = document.querySelectorAll('.card');
    cardsLen = divsCards.length;

    for (i = 0; i < cardsLen; i++) {
        var currentCard = divsCards[i];

        if (currentCard.dataset.card === card && currentCard.dataset.uid !== uid) {
            // We have found a match
            return currentCard;
        }
    }
} 

For the specific inquiry at the question, without rewriting the entire code, you can create a variable where the value is the current element in the for loop, use .filter() chained to the array containing all elements to exclude the current index from the results, then compare the data-* attribute valaues

  function findPair() {
    let divsCards = Array.from(document.querySelectorAll('.card'));
    for (let i = 0; i < divsCards.length; i++) {
      let currentCard = divsCards[i]; // current element at index `i`
      divsCards.filter((_, index) => index !== i) // exclude current element          
      .forEach(function(card) {
        // compare remainder of elements to excluded element
        if (card.dataset.card === currentCard.dataset.card) {
          currentCard.classList.add('flipped');
        }
      });
    }
  }

jsfiddle https://jsfiddle.net/hnud8tfx/

You could do something like this. Idea is to add an event listener to all the cards and on click you memorize the card (up to two max). Once two have been chosen (that previously has not been chosen) you check to see if they match.

If they do, add them to the done list (used to check when the game is done (not implemented)) and empty the flip list and update the class names.

 const flipped = []; const done = []; const cards = Array.from( document.querySelectorAll(".container > .card") ); const scoreEle = document.getElementById("score"); cards.forEach(card=>{ card.addEventListener("click", function(){ if(flipped.length < 2 && !this.classList.contains("flip")){ flipped.push(card); this.classList.add("flip"); card.innerText = card.dataset.card; setTimeout(check, 500); } }) }) function check(){ if(flipped.length != 2) return; const [c1, c2] = flipped; if(c1.dataset.card === c2.dataset.card){ done.push(c1,c2); } else { flipped.forEach(c=>{ c.classList.remove("flip") c.innerText = ""; }); } flipped.length = 0; } 
 .container { display: flex; flex-wrap: wrap; justify-content: space-between; } .card { margin-top: 10px; width: 100px; height: 100px; background-color: green; } .card.flip { background-color: blue; } 
 <div class="container"> <div class="card" data-card="1" ></div> <div class="card" data-card="7" ></div> <div class="card" data-card="5" ></div> <div class="card" data-card="1" ></div> <div class="card" data-card="7" ></div> <div class="card" data-card="5" ></div> </div> 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM