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 =“test”它的警告:t,e,s,t ...有关如何的任何建议得到每个元素id是该类的一部分是值得赞赏的,因为我似乎无法弄清楚这一点..谢谢。
$.each('test', function() {
alert(this)
});
2 个解决方案
#1
122
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')。每个(函数....
This is the specific form of .each()
that iterates over a jQuery object.
这是迭代jQuery对象的.each()的特定形式。
The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t
.
您使用的表单会迭代任何类型的集合。所以你基本上迭代了一个字符数组t,e,s,t。
Using that form 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.
...将与上面的示例具有相同的结果。
#2
23
patrick dw's answer is right on.
帕特里克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);
#1
122
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')。每个(函数....
This is the specific form of .each()
that iterates over a jQuery object.
这是迭代jQuery对象的.each()的特定形式。
The form you were using iterates over any type of collection. So you were essentially iterating over an array of characters t,e,s,t
.
您使用的表单会迭代任何类型的集合。所以你基本上迭代了一个字符数组t,e,s,t。
Using that form 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.
...将与上面的示例具有相同的结果。
#2
23
patrick dw's answer is right on.
帕特里克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);