我想要做的是计算当前页面中具有相同类的所有元素,然后我将使用它添加到输入表单的名称。基本上我允许用户点击<span>
,然后通过这样做添加另一个更多相同类型的项目。但我想不出用jQuery / JavaScript简单计算所有这些的方法。
我打算把这个项目命名为像name="whatever(total+1)"
这样的东西,如果有人有一个简单的方法可以做到这一点,我会非常感激,因为JavaScript并不完全是我的母语。
应该是这样的:
// Gets the number of elements with class yourClass
var numItems = $('.yourclass').length
作为旁注,在链接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');
});
}
获取引用同一类的元素数量的计数就像这样简单
<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);
尝试
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>