Javascript jQuery 按类计算元素 - 实现这一点的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2727303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:40:04  来源:igfitidea点击:

jQuery counting elements by class - what is the best way to implement this?

javascriptjquerycsselement

提问by 133794m3r

What I'm trying to do is to count all of the elements in the current page with the same class and then I'm going to use it to be added onto a name for an input form. Basically I'm allowing users to click on a <span>and then by doing so add another one for more of the same type of items. But I can't think of a way to count all of these simply with jQuery/JavaScript.

我想要做的是计算当前页面中具有相同类的所有元素,然后我将使用它添加到输入表单的名称中。基本上,我允许用户单击一个<span>,然后通过这样做为更多相同类型的项目添加另一个。但我想不出一种方法来简单地用 jQuery/JavaScript 计算所有这些。

I was going to then name the item as something like name="whatever(total+1)", if anyone has a simple way to do this I'd be extremely grateful as JavaScript isn't exactly my native tongue.

然后我打算将项目命名为类似的名称name="whatever(total+1)",如果有人有一个简单的方法来做到这一点,我将非常感激,因为 JavaScript 并不是我的母语。

回答by PatrikAkerstrand

Should just be something like:

应该是这样的:

// Gets the number of elements with class yourClass
var numItems = $('.yourclass').length






As a side-note, it is often beneficial to check the length property before chaining a lot of functions calls on a jQuery object, to ensure that we actually have some work to perform. See below:


作为旁注,在链接 jQuery 对象上的大量函数调用之前检查 length 属性通常是有益的,以确保我们实际上有一些工作要执行。见下文:

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');
    });
}

回答by Jonathan

Getting a count of the number of elements that refer to the same class is as simple as this

获取引用同一类的元素数量的计数就像这样简单

<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>

回答by Max Shawabkeh

var count = $('.' + myclassname).length;

回答by Alastair Pitts

for counting:

计数:

$('.yourClass').length;

$('.yourClass').length;

should work fine.

应该工作正常。

storing in a variable is as easy as:

存储在变量中就像这样简单:

var count = $('.yourClass').length;

var count = $('.yourClass').length;

回答by Nilesh Darade

HTML:

HTML:

<div>
    <img src='' class='class' />
    <img src='' class='class' />
    <img src='' class='class' />
</div>

JavaScript:

JavaScript:

var numItems = $('.class').length; 

alert(numItems);

Fiddle demo for inside only div

仅用于内部 div 的小提琴演示

回答by Kamil Kie?czewski

try

尝试

document.getElementsByClassName('myclass').length

let num = document.getElementsByClassName('myclass').length;
console.log('Total "myclass" elements: '+num);
.myclass { color: red }
<span class="myclass" >1</span>
<span>2</span>
<span class="myclass">3</span>
<span class="myclass">4</span>