Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
Bucle anidado que solo representa el último elemento indexado usando jquery appendPe

Realicé una llamada ajax a una API de bebidas y anidé un bucle para extraer los ingredientes y mostrarlos en la página. El bucle anidado consuela los ingredientes correctamente, pero cuando uso jquery para agregar los resultados a la página, solo se muestra el elemento en el último índice. Sé que hay valores nulos que iba a eliminar con una declaración if después de que los mostrara.

función mostrar datos de la bebida (nombre de la bebida) {

 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); } })

} ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Debido a que var ingList está dentro del bucle, no se agrega, sino que se crea uno nuevo cada vez.

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

Declare la variable fuera del bucle y agregue <li> para cada elemento.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!