简体   繁体   中英

Detecting matching class names dynamically with jQuery/JavaScript

I'm working on a pairing game from scratch, to help me learn JavaScript and jQuery. For each hurdle I research until I find an answer, but I seem to have hit a roadblock! Aplogies in advance if this is a duplicate question, but I have been unable to find anything that works.

Here is a simplified version of my problem:

A list is generated dynamically with pairs of classes, ready for matching;

<ul>
<li class="flip card1"></li>
<li class="flip card1"></li>
<li class="flip card2"></li>
<li class="flip card2"></li>
<li class="flip card3"></li>
<li class="flip card3"></li>
</ul>

If the user has successfully identified the matching li's, they click on them so that they are 'active' like so;

<ul>
<li class="flip card1"></li>
<li class="flip card1"></li>
<li class="flip card2 active"></li>
<li class="flip card2 active"></li>
<li class="flip card3"></li>
<li class="flip card3"></li>
</ul>

The script needs to detect when li's with the class of active also share a matching card class. This will then remove the class of 'active' and add the class 'matching' to identify that they have successfully matched.

I have been thinking like this;

var numActive = $('.active').attr('class');
var numPairs = $(numActive).length;

if (numPairs == 2) {
$('.active').addClass('matching').remove class('active');
}

I have also thought about something to this effect;

<ul>
<li class="flip card0"></li>
<li class="flip card0"></li>
<li class="flip card00 active"></li>
<li class="flip card00 active"></li>
<li class="flip card000"></li>
<li class="flip card000"></li>
</ul>

var matched = $('.active').attr('class').length();
if(matched occurs twice with class of active){
$('.active').addClass('matching').remove class('active');
}

Many thanks in advance!

Assuming that you need to:

  • check if two items have the class .active
  • and have same class (excluding flip and active )
if ($(".active").length === 2) {
    var class1 = (" " + $(".active:eq(0)").attr("class") + " ")
        .replace(" flip ", "")
        .replace(" active ", "")
        .replace(/^ +| +$/g, "");
    var class2 = (" " + $(".active:eq(1)").attr("class") + " ")
        .replace(" flip ", "")
        .replace(" active ", "")
        .replace(/^ +| +$/g, "");
    if (class1 === class2) {
        $(".active").toggleClass("active matching");
    }
}

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