Jquery push all li's ID's into array

╄→尐↘猪︶ㄣ 提交于 2019-12-21 20:14:28

问题


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


回答1:


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);
});



回答2:


or you can use $.map():

var ids = $('ul#jdLists li').map(function () {
   return this.id;
}).get();



回答3:


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


来源:https://stackoverflow.com/questions/13993694/jquery-push-all-lis-ids-into-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!