简体   繁体   English

HTML中的JQuery类计数

[英]JQuery Classes Count in HTML

I have a HTML which is receive input from users. 我有一个HTML,可以接收用户的输入。 My job is to count cards they enter and style these cards. 我的工作是计算输入的卡片并为这些卡片设定样式。 Cards are placed inside <section> . 卡放在<section>

Problems: My Jquery is only counting and works well in one section. 问题:我的Jquery仅在计数,并且在一个部分中运行良好。 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. 我的下面代码显示用户何时输入2个部分:第一部分中的卡片应为蓝色,第二部分中的卡片应为红色,但现在它们全为蓝色。

jsfiddle 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 : 您需要遍历各节,然后使用this关键字检查:

 $('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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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