Jquery push all li's ID's into array

2019-04-11 18:47发布

I need to push all my ID's into an array, both ways I've tried this only pushes the first ID into the array:

  var some = [];
  $('ul#jdLists li').each(function () {
   some.push([$('ul#jdLists li').attr("id")]);
  });

This returns the correct number of items in the array but with the ID of the first li

or

    var some = [];                
    some.push([$('ul#jdLists li').attr("id")]);

this returns a single item with the first li ID

thanks

3条回答
闹够了就滚
2楼-- · 2019-04-11 19:09

This piece of code: some.push([$('ul#jdLists li').attr("id")]); will push id of first li found by ul#jdLists li selector, what you need to do is to get id of each li, which can be done inside each function:

var some = [];
$('ul#jdLists li').each(function () {
   some.push($(this).attr("id"));
   // or
   some.push(this.id);
});
查看更多
Bombasti
3楼-- · 2019-04-11 19:21
var some = [];
$('ul#jdLists li').each(function (i, el) {
   some.push(el.id);
});
查看更多
迷人小祖宗
4楼-- · 2019-04-11 19:34

or you can use $.map():

var ids = $('ul#jdLists li').map(function () {
   return this.id;
}).get();
查看更多
登录 后发表回答