从类选择器中获取每个元素值

时间:2012-11-30 18:29:36

标签: jquery

  

可能重复:
  Get attribute values as array from selection of elements using jQuery

我正在尝试从元素列表中获取id

我有

<div class='test' id='123'> </div>
<div class='test' id='1243'> </div>

<div class='test' id='1223'> </div>
<div class='test' id='1423'> </div>
<div class='test' id='1223'> </div>
<div class='test' id='1253'> </div>

我想获得每个div的id

我有

var idarray=[];

var id= $('.test').attr('id'); //would only get the first 123 id.

idarray.push(id)

如何在我的案例中获取每个id到idarray?谢谢你的帮助

6 个答案:

答案 0 :(得分:5)

您可以使用

var idarray = $('.test').map(function(){return this.id}).get();

答案 1 :(得分:2)

您可以使用jquery .map()函数创建数组,如下所示:

var id = $('.test').map(function() {
   return $(this).attr('id');
}).get();

答案 2 :(得分:2)

您可以通过简单的每个循环来完成此任务。

var idarray=[];
$('.test').each(function(){idarray.push(this.id);})

答案 3 :(得分:1)

使用.each循环,如下所示:

var idarray = [];

$(".test").each(function() {
    idarray.push($(this).attr("id"));
});

答案 4 :(得分:1)

这是一个可能的解决方案:

ids = [];
$("div").each(function() {
    $this = $(this);
    ids.push($this.attr("id"));
});

这会产生一个id s的数组。

答案 5 :(得分:1)

在idarray中使用以下代码来识别

var idarray = [];
$.each($(".test"),function(index,value)
   {
idarray.push($(value).attr("id"));
   });

检查小提琴

http://jsfiddle.net/E8Rjs/5/ 感谢

相关问题