我希望将id从数组中的元素集合中保存,但只保存了最后一个元素的id。
小提琴
HTML:
<div class="div" id="d1">DIV-1</div>
<div class="div" id="d2">DIV-2</div>
<div class="div" id="d3">DIV-3</div>
<div class="div" id="d4">DIV-4</div>
<div class="div" id="d5">DIV-5</div>
<hr>
<div id="test" style="background-color:yellow;"></div>联署材料:
$('.div').each(function(n){
var test = new Array();
test = $(this).attr('id');
$('#test').html(test);
});发布于 2013-11-15 11:53:24
使用map()
var ids = $('.div').map(function() {
return this.id;
}).get();
$('#test').text(ids.join(','));例琴
API参考
发布于 2013-11-15 11:55:20
你可以用.map()来做
$('#test').html($('.div').map(function(){
return $(this).attr('id');
}).get().join());演示:http://jsfiddle.net/uNEcX/2/
发布于 2013-11-15 11:54:32
var test = new Array();
$('.div').each(function(n){
test.push($(this).attr('id'));
$('#test').html(test);
});这将得到所有的数据,您在循环的每一次迭代中都重新初始化了数组。
https://stackoverflow.com/questions/20000465
复制相似问题