如何计算具有特定类的 DIV
Posted
技术标签:
【中文标题】如何计算具有特定类的 DIV【英文标题】:How to count DIV with specific classes 【发布时间】:2021-02-23 03:36:54 【问题描述】:我想计算具有特定类名的DIV,然后在H2标签中添加数字
期望的结果
<h2 id="result">5 Cards found</h2>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
【问题讨论】:
这是任何 jQuery 教程的主题 -> jQuery Learning Center How much research effort is expected of Stack Overflow users? -> How can I count the number of elements with same class?, Count elements with jQuery, jQuery counting elements by class - what is the best way to implement this? 好吧,我找到了这些,但不知道如何添加到 h2 或 div 中。所有这些结果都打印到控制台。 这只是 jQuery 教程的另一点,或者上面提到的学习中心,或者...... - 但不是这样(即使你肯定会找到与该确切主题相关的问题) 或者您将您所知道的添加到问题中,这样我们人们就不会在您已经知道的部分上浪费时间。 【参考方案1】:这是你的活生生的例子。
$(document).ready(function()
$('#result').html($('.post_card').length + " Cards found");
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id="result">5 Cards found</h2>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
【讨论】:
【参考方案2】:你可以这样做:
$('#result .count').html($('.post_card').length)
我已经在你的 html 中添加了一个跨度作为计数值的容器,那么我们不必在返回中包含文本 Cards found
。
演示
$('#result .count').html($('.post_card').length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 id="result"><span class="count"></span> Cards found</h2>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
【讨论】:
【参考方案3】:你可以喜欢这个,使用length
。
var count_post = $(".container .post_card").length;
var count_post_no = $(".container .no_post_card").length;
$('#result').append(count_post);
$('#result2').append(count_post_no);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="post_card"></div>
<div class="no_post_card"></div>
<div class="no_post_card"></div>
<div class="no_post_card"></div>
</div>
<h2 id="result">Result (post_card): </h2>
<br>
<h2 id="result2">Result (no_post_card): </h2>
【讨论】:
以上是关于如何计算具有特定类的 DIV的主要内容,如果未能解决你的问题,请参考以下文章