jQuery,使用.each 获取类中每个元素的ID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3485825/
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
jQuery, get ID of each element in a class using .each?
提问by Rick
I'm trying this to get the id
of each element in a class
but instead it's alerting each name of the class separately, so for class="test"
it's alerting: t
, e
, s
, t
... Any advice on how to get the each element id
that is part of the class
is appreciated, as I can't seem to figure this out.. Thanks.
我想这让id
各元素在class
,而是它的单独提醒类的每一个名字,所以class="test"
它的提醒:t
,e
,s
,t
...如何让每一个元素任何意见id
是部分class
是感谢,因为我似乎无法弄清楚这一点..谢谢。
$.each('test', function() {
alert(this)
});
回答by user113716
Try this, replacing .myClassName
with the actual name of the class (but keep the period at the beginning).
试试这个,用.myClassName
类的实际名称替换(但将句点保留在开头)。
$('.myClassName').each(function() {
alert( this.id );
});
So if the class is "test", you'd do $('.test').each(func...
.
所以如果课程是“测试”,你会做$('.test').each(func...
.
This is the specific form of .each()
that iterates over a jQuery object.
这是.each()
遍历 jQuery 对象的特定形式。
The form you were using iterates over anytype of collection. So you were essentially iterating over an array of characters t,e,s,t
.
您使用的表单可以遍历任何类型的集合。所以你本质上是在迭代一个字符数组t,e,s,t
。
Using thatform of $.each()
, you would need to do it like this:
使用这种形式的$.each()
,您需要这样做:
$.each($('.myClassName'), function() {
alert( this.id );
});
...which will have the same result as the example above.
...这将具有与上述示例相同的结果。
回答by jessegavin
patrick dw's answer is right on.
patrick dw的答案是正确的。
For kicks and giggles I thought I would post a simple way to return an array of all the IDs.
对于踢球和傻笑,我想我会发布一种简单的方法来返回所有 ID 的数组。
var arrayOfIds = $.map($(".myClassName"), function(n, i){
return n.id;
});
alert(arrayOfIds);