请求补全代码:分别统计各容器内.resp-container数量并分配对应类
Solution: Assign Classes to .resp-container Elements Based on Per-Container Count
It looks like your current code is calculating the total number of .resp-container elements across all containers, instead of counting them individually per parent container. That's why the class is being applied uniformly to all elements, not based on how many are in each container.
Here's the corrected approach that handles each container separately:
$(document).ready(function(){ // Loop through each parent container (replace ".container" with your actual container selector) $(".container").each(function() { const $currentContainer = $(this); const $respElements = $currentContainer.find(".resp-container"); const elementCount = $respElements.length; switch(elementCount) { case 1: $respElements.addClass("full-resp"); break; case 2: $respElements.addClass("half-resp"); break; case 3: $respElements.addClass("third-resp"); // Adjust class name as needed break; case 4: $respElements.addClass("quarter-resp"); // Add more cases for higher counts break; default: // Optional: Handle unexpected counts with a default class $respElements.addClass("default-resp"); break; } }); });
Key Changes Explained:
.each()on containers: We iterate over each parent container instead of targeting all.resp-containerelements at once. This lets us handle each group separately.- Per-container count: For each container, we find only its child
.resp-containerelements and count those, not the global total. - Targeted class addition: The class is added only to the elements inside the current container, based on that container's specific count.
Important Notes:
- Replace
.containerwith the actual CSS selector for your parent containers (e.g.,.card,.section, or whatever wraps your.resp-containerelements). - Add more
casestatements to the switch block if you need to handle counts greater than 4, using the appropriate class names for those cases. - The
defaultcase is optional but useful for handling unexpected counts (like 5+ elements) with a fallback class.
内容的提问来源于stack exchange,提问作者Aleks Pvn
相关产品推荐
相关产品推荐

