使用 jQuery 将所有具有类的对象加载到数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/554348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loading all objects with class into an array using jQuery
提问by user67033
I have a bunch of div's on my page with class testClass.
我的页面上有一堆带有 testClass 类的 div。
I want to load them into an array and then check the array's size.
我想将它们加载到一个数组中,然后检查数组的大小。
But its not working?
但它不起作用?
myArray = $('testClass');
alert(myArray.count);
What's wrong?
怎么了?
回答by leftnode
You have:
你有:
myArray = $('testClass');
alert(myArray.count);
You want:
你要:
myArray = $('.testClass');
alert(myArray.length);
Notice, first, the . for testClass. Then, myArray is a JavaScript object, so you have access to the length key.
请注意,首先, . 用于测试类。然后,myArray 是一个 JavaScript 对象,因此您可以访问长度键。
回答by jonstjohn
The code that you have provided returns an iterable jQuery object, but not an array. Also, you have made a mistake in your class selector.
您提供的代码返回一个可迭代的 jQuery 对象,而不是一个数组。此外,您在类选择器中犯了一个错误。
For check the size of that jQuery object, you can use:
要检查该 jQuery 对象的大小,您可以使用:
var $j_object = $(".testClass");
alert($j_object.size());
To loop over that object, you can use the each() function:
要遍历该对象,您可以使用 each() 函数:
var $j_object = $(".testClass");
$j_object.each( function(i) { doSomethingHere(); } );
Check the jQuery documentation for more information on how to use each().
有关如何使用 each() 的更多信息,请查看 jQuery 文档。
One other note. If you want to do something with the dom object within the each function, you can refer to 'this'. To get the jQuery object from the dom object, you can use $(this).
另一注。如果你想对 each 函数中的 dom 对象做一些事情,你可以参考“this”。要从 dom 对象中获取 jQuery 对象,可以使用 $(this)。
Also, the $ sign is completely optional, but can help to distinguish between jQuery objects and other variables, such as those that denote dom elements.
此外,$ 符号是完全可选的,但可以帮助区分 jQuery 对象和其他变量,例如那些表示 dom 元素的变量。
回答by tanathos
You can do this without using an array:
您可以在不使用数组的情况下执行此操作:
$('.testClass').length
That's all.
就这样。