如何获取具有相同类名的元素的每个属性 id?
var id = $('.class').attr('id');
但是当我使用console.log时,它只返回一个id,即使我有多个id和多个具有相同类的div。
var ids = $('.class').map(function() {
return $(this).attr('id');
});
console.log(ids);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="class" id="1"></div>
<div class="class" id="2"></div>
<div class="class" id="3"></div>
var i = 0;
var ids = [];
$(".class").each(function(){
ids[i++] = $(this).attr("id"); //this.id
});
map()
更好。 - A. Wolffvar ids = $('.class').map(function() {
return this.id;
}).get();
console.log(1, ids);
//For modern browsers with arrow functions
ids = $('.class').map((i, item)=>item.id).get();
console.log(2, ids);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="class" id="a"></div>
<div class="class" id="b"></div>
<div class="class" id="c"></div>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery.map demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div class="map-test" id="1"></div>
<div class="map-test" id="21"></div>
<div class="map-test" id="31"></div>
<div class="map-test" id="41"></div>
<div class="map-test" id="51"></div>
<div class="map-test" id="61"></div>
<div class="map-test" id="71"></div>
<div class="map-test"></div>
<script>
var arr = jQuery.map(jQuery('.map-test'),function(n,i){
return jQuery(n).attr('id');
});
console.log(arr);
//will print ["1", "21", "31", "41", "51", "61", "71"]
</script>
</body>
</html>
ids = ids.toArray()
。 - gondwe