Loop Usage within the Append Function

Asked

Viewed 430 times

0

Hello, it is possible to use a loop inside the append function ?

I have the variable (presentation) in the code below. Let’s assume that this variable was a Vector, apeend?

<html>
    <body>

    </body>
 </html>

$(function(){
    var valorID="meuID";
    var apresentacao="meu nome";

    var a='<div id='+valorID+'>'+apresentacao+
              '<div id="a">presentacao</div>'+
          '</div>';
    $("body").append(a);
});
  • The ideal would not be to use the function append within a loop?

3 answers

3


If I understand correctly, you want one loop adding each value to the body, right? The method append can’t stand a loop inside it, but it can be used inside a loop. In the snippet below, I used a for(supposing that the arrangements apresentacao and valorID is the same size.

$(function(){

var valorID="ID";
var apresentacao=["meu nome","seu nome","nosso nome"];
$('body').append(`<div id="${valorID}"></div>`);
for(var i=0; i < apresentacao.length; i++){
   $(`#${valorID}`).append(`<p>${apresentacao[i]}</p>`)
}
$(`#${valorID}`).append('<div id="a">Apresentacao</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
    <body>

    </body>
</html>

2

Create an empty variable and concatenate to create the HTML and only after the loop call the .append with the variable with all HTML. Use x of the loop to create iddifferent s for each element as there cannot be ids repeated:

$(function(){
   var a = '';
   var valorID="meuID";
   var apresentacao=['nome 1','nome 2','nome 3'];
   
   for(var x=0; x<apresentacao.length; x++){
      a += '<div id='+ valorID+x +'>'+ apresentacao[x] +
      '<div id="a'+ x +'">presentacao</div>'+
      '</div>';
   }

   $("body").append(a);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Or you can use a function within the .append returning the variable a full:

$(function(){
   var a = '';
   var valorID="meuID";
   var apresentacao=['nome 1','nome 2','nome 3'];
   
   $("body").append(function(){
      
      for(var x=0; x<apresentacao.length; x++){
         a += '<div id='+ valorID+x +'>'+ apresentacao[x] +
         '<div id="a'+ x +'">presentacao</div>'+
         '</div>';
      }

      return a;
      
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1

I believe that’s what you want. Just include the desired HTML

$(function(){

var apresentacao = ["meu nome", "meu nome 2", "meu nome 3"];

for(i=0; i < apresentacao.length; i++)
{
        $("body").append(apresentacao[i]);
}

});

I hope it helps you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.