jQuery - 查找类中的所有ID

eye*_*eye 12 jquery class

假设我有一个像这样的html表:

<table>
<tr id="a" class="red"><td>test</td></tr>
<tr id="b" class="red"><td>test</td></tr>
<tr id="c" class="red"><td>test</td></tr>
<tr id="d" class="red"><td>test</td></tr>
<tr id="e" class="green"><td>test</td></tr>
<tr id="f" class="blue"><td>test</td></tr>
</table>
Run Code Online (Sandbox Code Playgroud)

我如何使用jQuery循环/获取类"red"的所有id?

Ant*_*ton 23

使用.each()

var idArray = [];
$('.red').each(function () {
    idArray.push(this.id);
});
Run Code Online (Sandbox Code Playgroud)


Aru*_*hny 7

使用$ .map()就像

//ids is an array of the element ids with class red
var ids = $('table .red').map(function(){
    return this.id
}).get()
Run Code Online (Sandbox Code Playgroud)

演示:小提琴


pal*_*aѕн 7

You can do this using the .map() method like:

var ids = $('.red').map(function () {
    return this.id;
}).get().join();

console.log(ids);  // Result: a,b,c,d 
Run Code Online (Sandbox Code Playgroud)

Explanation:-