简体   繁体   中英

JQuery Classes Count in HTML

I have a HTML which is receive input from users. My job is to count cards they enter and style these cards. Cards are placed inside <section> .

Problems: My Jquery is only counting and works well in one section. If users enter more than one sections, the code doesn't work. My code below shows when users enter 2 sections: cards in first section should be blue and cards in second section should be red, but now they are all blue.

jsfiddle

 var numCard = $('.cards').length; if (numCard == "2") { /* $('.cards').css('color', 'red'); */ $("section .cards").parent().addClass("two-cards"); } else if (numCard == "3") { $("section .cards").parent().addClass("three-cards"); } else { $('section .cards').parent().addClass("four-cards"); } 
 body { padding: 20px; font-family: Helvetica; } .two-cards .cards { color: red; } .three-cards .cards { color: green; } .four-cards .cards { color: blue; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <section> <div class="cards"> First Card </div> <div class="cards"> Second Card </div> <div class="cards"> Third Card </div> <div class="cards"> Third Card </div> </section> <p> <section> <div class="cards"> First Card </div> <div class="cards"> Second Card </div> </section> 

Working fiddle

You need to loop through the sections, then use this keyword to check :

 $('section').each(function() { var numCard = $('.cards', this).length; if (numCard == "2") { $(this).addClass("two-cards"); } else if (numCard == "3") { $(this).addClass("three-cards"); } else { $(this).addClass("four-cards"); } }); 
 body { padding: 20px; font-family: Helvetica; } .two-cards .cards { color: red; } .three-cards .cards { color: green; } .four-cards .cards { color: blue; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <section> <div class="cards"> First Card </div> <div class="cards"> Second Card </div> <div class="cards"> Third Card </div> <div class="cards"> Third Card </div> </section> <p> <section> <div class="cards"> First Card </div> <div class="cards"> Second Card </div> </section> </p> 

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