简体   繁体   中英

How do I store data in array within a loop jQuery

How do I store data in array within a loop?

    var images;
    var i = 0;

    $('#cover div').each(function()
    {
        alert($(this).attr('id'));
        //I should store id in an array
    });


    <div id="cover">
        <div id="slider_1"><p class="content">SLIDER ONE</p></div>
        <div id="slider_2"><p class="content">SLIDER TWO</p></div>
        <div id="slider_3"><p class="content">SLIDER THREE</p></div>
    </div>

Try this,

var arr = [];
i = 0;
$('#cover div').each(function()
{
        alert($(this).attr('id'));
        arr[i++] = $(this).attr('id');
        //I should store id in an array
});

other Way for getting id using javascript object instead of jquery for increasing performance.

var arr = [];
i = 0;
$('#cover div').each(function()
{
      arr[i++] = this.id;
});

Edit You can also use jQuery map()

Live Demo

arr = $('#cover div').map(function(){
    return this.id;
});

javascript Arrays have a method push(el) like this:

var images;
var i = 0;

$('#cover div').each(function()
{
    alert($(this).attr('id'));
    images.push($(this).attr('id'));
});

<div id="cover">
    <div id="slider_1"><p class="content">SLIDER ONE</p></div>
    <div id="slider_2"><p class="content">SLIDER TWO</p></div>
    <div id="slider_3"><p class="content">SLIDER THREE</p></div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM