jQuery 按类计数元素 - 实现此目的的最佳方法是什么?
我想做的是计算当前页面中具有相同类的所有元素,然后将其添加到输入表单的名称中。基本上,我允许用户单击 ,然后通过这样做添加另一个以获取更多相同类型的项目。但我想不出一种方法来简单地用 jQuery/JavaScript 来计算所有这些。
然后我打算将该项目命名为 name="whatever(total+1)"
之类的名称,如果有人有一个简单的方法来做到这一点,我将非常感激,因为 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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
应该是这样的:
顺便说一句,在链接 jQuery 对象上的许多函数调用之前检查 length 属性通常是有益的,以确保我们实际上有一些工作要做。见下文:
Should just be something like:
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:
获取引用同一类的元素数量的计数就这么简单
Getting a count of the number of elements that refer to the same class is as simple as this
HTML:
JavaScript:
仅限内部 div 的 Fiddle 演示
HTML:
JavaScript:
Fiddle demo for inside only div
用于计数:
$('.yourClass').length;
应该可以正常工作。
存储在变量中就像这样简单:
var count = $('.yourClass').length;
for counting:
$('.yourClass').length;
should work fine.
storing in a variable is as easy as:
var count = $('.yourClass').length;
尝试
try