应该只是像这样:
// 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');
});
}