James James - 6 months ago 19
Javascript Question

Converting for into jQuery each

Really new to JS and wondering if someone knew how i can change the following into using jQuery each:

current:

for (var i in basket){
var item = basket[i];
var row = "<tr><td><img src='" + item.image + "' class='thumbnail'/></td><td>" + item.title + "</td><td>" + item.sku + "</td><td>&pound;" + item.price + "</td><td>" + "<a href='#' class='button primary small delete-item' data-item='"+ i +"'>Delete</a></td></tr>";
$(".basket-content").append(row);
}


attempted:

$.each(function(i, basket){
for (var i in basket){
var item = basket[i];
var row = "<tr><td><img src='" + item.image + "' class='thumbnail'/></td><td>" + item.title + "</td><td>" + item.sku + "</td><td>&pound;" + item.price + "</td><td>" + "<a href='#' class='button primary small delete-item' data-item='"+ i +"'>Delete</a></td></tr>";
$(".basket-content").append(row);
}
});

Answer

The first argument to $.each is the array/object you want to iterate over. The arguments to the function are the index and the element (so you don't need to assign item yourself).

$.each(basket, function(i, item) {
    var row = "<tr><td><img src='" + item.image + "' class='thumbnail'/></td><td>" + item.title + "</td><td>" + item.sku + "</td><td>&pound;" + item.price + "</td><td>" + "<a href='#' class='button primary small delete-item' data-item='"+ i +"'>Delete</a></td></tr>";
    $(".basket-content").append(row);
});
Comments