lundi 10 août 2015

Fill divs with strings from array

I want to have divs fill with text stored in a jquery array randomly. My html looks like

<div class="row">
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
    <div class="cell">&nbsp;</div>
</div>

In my jQuery I have an array that looks like

var fruits = ["Apple", "Pear", "Orange"]

Each cell should be filled with a fruit randomly but I am stuck with iterating over the correctly and picking random values for each div with the class cell. This code obviously does not work:

$.each(fruits), function(fruit) {
    var fruit = fruits[Math.floor(Math.random()*fruits.length)];
    $('.row .cell').text(fruit);
}

How can I make the random guess happen exactly 5 times and fill the divs correctly?




Aucun commentaire:

Enregistrer un commentaire