开发者

How can jQuery convert my ordered list into an array?

开发者 https://www.devze.com 2023-02-03 08:45 出处:网络
This is my list: <ol> <li>Audi</li> <li>K开发者_StackOverflow中文版awasaki</li>

This is my list:

<ol>
    <li>Audi</li>
    <li>K开发者_StackOverflow中文版awasaki</li>
    <li>Vauxhall</li>
</ol>

What is the jQuery function that will transform the list items into an array?

var cars;
$('li').map(function() {
    // converts the ordered list into a javascript array named 'cars'
}); 

Thanks!


If what you want is an array of the li DOM elements you can just use jQuery's toArray():

var cars = $('li').toArray();

If what you need is an array containing ['audi', 'kawasaki',...] then:

var cars = [];
$('li').each(function(i, elem) {
    cars.push($(elem).text());
});


$('li').map(function() { 
  return $(this).val();
}).get();
0

精彩评论

暂无评论...
验证码 换一张
取 消