Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

88
Visualizações
Nested loop only rendering last indexed item using jquery appendPe

Performing an ajax call to a drinks api and I've nested a loop to pull the ingredients out and render them to the page. The nested loop consoles the ingredients correctly but when I use jquery to append the results to the page only the item in the last index is displayed. I know there are null values I was going to remove them with an if statement after I got them to show.

function displayDrinkData(drinkName) {

var queryURL = "https://thecocktaildb.com/api/json/v1/1/search.php?s=" + drinkName

$.ajax({
    url: queryURL,
    method: "GET"
}).then(function (response) {
    console.log(response);

    var results = response.drinks;

    for (var i = 0; i < results.length; i++) {

        console.log(results[i]);

        var eachDrink = results[i];

        var drinkDiv = $("<div>");

        var drinkName = results[i].strDrink;

        for (var k = 1; k < 16; k++) {

            console.log(eachDrink['strIngredient' + k]);

            var ingList = $("<ul>").text("Ingredients: " + eachDrink['strIngredient' + k])              

        }

        var pOne = $("<p>").text("Drink name: " + drinkName);

        var drinkInstructions = results[i].strInstructions;

        var pTwo = $("<p>").text("Instructions: " + drinkInstructions);
        var drinkImage = $("<img>");

        drinkImage.attr("src", results[i].strDrinkThumb);

        drinkDiv.append(pOne);
        drinkDiv.append(ingList);
        drinkDiv.append(pTwo);
        drinkDiv.append(drinkImage);

        $("#drinks-view").append(drinkDiv);
    }

})

} enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Because var ingList is inside loop, not appending, but creating a new one every time.

var ingList = $("<ul>");
for (var k = 1; k < 16; k++) {
    console.log(eachDrink['strIngredient' + k]);
    ingList.append($('<li>').text("Ingredients: " + eachDrink['strIngredient' + k]));              
}

Declare variable outside loop, and append <li> for each element.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda