Using Loop within the Append Function

0

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

I have the variable (presentation) in the code below. Let's suppose that this variable is a Vector, as it would show its values inside the function 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);
});
    
asked by anonymous 05.07.2018 / 20:49

3 answers

3

If I understand correctly, you want a loop that adds each value to body , right? The append method does not support a loop within it, but it can be used within a loop. In the snippet below, I used a for (assuming that the apresentacao and valorID arrays have 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>
    
05.07.2018 / 20:55
2

Create an empty variable and go concatenating to create the HTML and only after the loop call the .append with the variable with all HTML. Use the x of the loop to create id s for each element, since there can not be id s 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>

Oryoucanuseafunctioninside.appendbyreturningthevariableafull:

$(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>
    
05.07.2018 / 21:32
1

I believe this is 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 that helps you.

    
05.07.2018 / 21:03