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.append
byreturningthevariablea
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>