简体   繁体   中英

jQuery array to unordered list

I have the following array:

var sherbert = [{ 
    flavor: "orange mango",
    cost: 2
},{
    flavor: "lemon lime",
    cost: 4
}];

Using jQuery how can I create a function that writes these as LI items like:

<li>flavor : orange mango<span>cost : 2</span></li>
<li>flavor : lemon lime<span>cost : 4</span></li>

Something like this should work, I did not test this code.

here are the documentation for jquerys each and append functions:

http://api.jquery.com/each/

http://api.jquery.com/append/

$listSelector = $("#list") //Your list element

$.each(sherbert, function(i, obj) {
    $listSelector.append("<li>flavor : "+obj.flavor+"<span>cost : "+obj.cost+"</span></li>")
});

Iterate over your sherbert object and add the new HTML as a new li in your desired list.

$.each(sherbert, function(index, dessert) {
    var new_html = "Flavor : " + dessert.flavor + "<span>cost : " + dessert.cost + "</span>";
    $('ul').append($('<li></li>').html(new_html));
});
<script>
var sherbert = [{ 
    flavor: "orange mango",
    cost: 2
},{
    flavor: "lemon lime",
    cost: 4
}];
$(document).ready(function(){
    $(sherbert).each(function(i, el){
        var li = document.createElement('li');
        li.innerHTML = "flavor : " + el.flavor + " <span>cost : " + el.cost + "</span>";
        $("#listItems")[0].appendChild(li);
    });
});
</script>
<body>
    <ul id="listItems">
    </ul>
</body>

Here you go:

var ul = $('<ul>');

for (var i = 0; i < sherbet.length; i++ ) {
    var li = $('<li>');
    var item = sherbet[i];
    for(var key in item) {
        var span = $('<span>');
        var text = key + ": " + item[key]; // flavour: orange
        span.html(text); // <span>flavour: orange</span>
        li.append(span); // <li><span>flavour: orange</span><span>cost: 2</span></li>
    }
ul.append(li);
}

Here, you don't really have to hard code any values such as 'flavour' or 'cost'. This code gives you flexibility to alter these texts into something else or add something to it like "size: 10oz" etc.
You just gotta add these additonal values to your array and this code will handle it all!

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