我想要做的是计算当前页面中具有相同类的所有元素,然后我将使用它添加到输入表单的名称中。基本上,我允许用户单击一个<span>,然后通过这样做为更多相同类型的项目添加另一个。但我想不出一种方法来简单地用 jQuery/JavaScript 计算所有这些。
然后我打算将项目命名为类似的名称name="whatever(total+1)",如果有人有一个简单的方法来做到这一点,我将非常感激,因为 JavaScript 并不是我的母语。
我想要做的是计算当前页面中具有相同类的所有元素,然后我将使用它添加到输入表单的名称中。基本上,我允许用户单击一个<span>,然后通过这样做为更多相同类型的项目添加另一个。但我想不出一种方法来简单地用 jQuery/JavaScript 计算所有这些。
然后我打算将项目命名为类似的名称name="whatever(total+1)",如果有人有一个简单的方法来做到这一点,我将非常感激,因为 JavaScript 并不是我的母语。
应该是这样的:
// Gets the number of elements with class yourClass
var numItems = $('.yourclass').length
作为旁注,在链接 jQuery 对象上的许多函数调用之前检查长度属性通常是有益的,以确保我们实际上有一些工作要执行。见下文:
var $items = $('.myclass');
// Ensure we have at least one element in $items before setting up animations
// and other resource intensive tasks.
if($items.length)
{
  $items.animate(/* */)
    // It might also be appropriate to check that we have 2 or more
    // elements returned by the filter-call before animating this subset of 
    // items.
    .filter(':odd')
      .animate(/* */)
      .end()
    .promise()
    .then(function () { 
       $items.addClass('all-done');
    });
}
获取引用同一类的元素数量的计数就像这样简单
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function() {
                alert( $(".red").length );
            });
        </script>
    </head>
    <body>
        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
    </body>
</html>
var count = $('.' + myclassname).length;
计数:
$('.yourClass').length;
应该工作正常。
存储在变量中非常简单:
var count = $('.yourClass').length;
HTML:
<div>
    <img src='' class='class' />
    <img src='' class='class' />
    <img src='' class='class' />
</div>
    
JavaScript:
var numItems = $('.class').length; 
        
alert(numItems);