如何从同一个类获取div id并循环id
例如
我试过,但只获得1个ID结果。这是我的代码:
var ids = $('.test').map(function() {
var resID = $(this).attr('id');
console.log(resID);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1" class="test">A</div>
<div id="2" class="test">B</div>
<div id="3" class="test">C</div>
<div id="4" class="test">D</div>
&#13;
答案 0 :(得分:3)
var ids = $('.test').map(function() {
return $(this).attr('id');
}).get();
console.log(ids)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1" class="test">A</div>
<div id="2" class="test">B</div>
<div id="3" class="test">C</div>
<div id="4" class="test">D</div>
答案 1 :(得分:1)
你可以使用jquery .each
$( ".test" ).each(function( index ) {
console.log( index + ": " + $( this ).attr('id') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1" class="test">A</div>
<div id="2" class="test">B</div>
<div id="3" class="test">C</div>
<div id="4" class="test">D</div>