假设我有一个像这样的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)
使用$ .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)
演示:小提琴
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:-
Here the below code:-
$('.red').map(function () {
return this.id;
})
Run Code Online (Sandbox Code Playgroud)
we are passing each element in the current matched set .red through a function, producing a new jQuery object containing the return values, which is the id of the each element.
So, the above code results in a new jQuery object like:
["a", "b", "c", "d", prevObject: jQuery.fn.init[4], context: document]
Run Code Online (Sandbox Code Playgroud)Next, .get() is used to retrieve the DOM elements matched by the new jQuery object above. So, after using .get() our result is like:
["a", "b", "c", "d"]
Run Code Online (Sandbox Code Playgroud)Next, .join() method joins all elements of an array (which we got after using .get()) into a string like:
a,b,c,d
Run Code Online (Sandbox Code Playgroud)
If we use .join(', ') we can get some space after comma like:
a, b, c, d
Run Code Online (Sandbox Code Playgroud)
or a .join('~') would result in:
a~b~c~d
Run Code Online (Sandbox Code Playgroud)
You can always modify the separator in the .join() based on your requirement.
var ids = $('.red').map(function() {
return this.id;
}).get().join();
console.log(ids); // Result: a,b,c,dRun Code Online (Sandbox Code Playgroud)
.red{color:red;}
.green{color:green;}
.blue{color:blue;}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<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)