jQuery按元素计数元素;什么是实现这个的最好的方法? [英] jQuery counting elements by class; what is the best way to implement this?

查看:198
本文介绍了jQuery按元素计数元素;什么是实现这个的最好的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

然后我会把这个项目命名为 name =whatever(total + 1),如果任何人有一个简单的方法,我会非常感谢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.

推荐答案

应该只是:

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




通常有利于在链接很多函数调用jQuery对象之前检查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:

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

这篇关于jQuery按元素计数元素;什么是实现这个的最好的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆