Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

javascript - jQuery按类计算元素 - 实现它的最佳方法是什么?(jQuery counting elements by class - what is the best way to implement this?)

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.(基本上我允许用户点击<span> ,然后通过这样做添加另一个用于更多相同类型的项目。) But I can't think of a way to count all of these simply with jQuery/JavaScript.(但我想不出用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并不完全是我的母语。)

  ask by 133794m3r translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.(作为旁注,在链接jQuery对象上的大量函数调用之前检查length属性通常是有益的,以确保我们实际上有一些工作要执行。)

See below:(见下文:)
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');
    });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...