You are traversing the array with each
, and the variable a
represents, at each iteration, a array
with the players of the team.
When playing the whole array a
within the li
, you are putting all players in the same item on the list.
The correct is to go through this array a
and put each player on their own li
. I also changed the variable name a
to make it clearer what it is (an array representing a team).
In addition, the text "Time x" must be outside the ul
, as indicated by reply from @sam. An alternative would be to throw it out, making each team part of another ul
external.
I mean, the structure is like this:
<ul>
<li>Time 1<li>
<li>
<ul>
<li>Jogador 1</li>
<li>Jogador 2</li>
...
</ul>
</li>
<li>Time 2<li>
<li>
<ul>
<li>Jogador 7</li>
<li>Jogador 8</li>
...
</ul>
</li>
</ul>
In jQuery it looks like this:
var array = [["Jogador1","Jogador2","Jogador3","Jogador4","Jogador5","Jogador6"],["Jogador7","Jogador8","Jogador9","Jogador10","Jogador11","Jogador12"]];
// criar lista externa (que vai ter todos os times)
$('body').append('<ul id="lista-times" style="list-style: none">');
// para cada time
$.each(array, function(i, time){
// cria um li com nome do time e outra lista ul para os jogadores
var idTime = 'time' + (i + 1);
$('#lista-times').append('<li>Time '+ (i + 1) + '</li><li><ul id="' + idTime + '">');
// loop para percorrer os jogadores do time
$.each(time, function(j, jogador) {
$('#' + idTime).append('<li>' + jogador + '</li>');
});
$('#lista-times').append('</ul></li>');
})
$('body').append('</ul>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You also have the option without jQuery:
var array = [["Jogador1","Jogador2","Jogador3","Jogador4","Jogador5","Jogador6"],["Jogador7","Jogador8","Jogador9","Jogador10","Jogador11","Jogador12"]];
// cria lista externa (que vai ter todos os times)
let ulExt = document.createElement('ul');
ulExt.style.listStyle = 'none';
// para cada time
array.forEach(function(time, i) {
// cria li com nome do time
let liTime = document.createElement('li');
liTime.appendChild(document.createTextNode('Time '+ (i + 1)));
ulExt.appendChild(liTime);
// cria outra lista ul para os jogadores
let ul = document.createElement('ul');
time.forEach( function (jogador, j) {
let li = document.createElement('li');
li.appendChild(document.createTextNode(jogador));
ul.appendChild(li);
});
let liJog = document.createElement('li');
liJog.appendChild(ul);
ulExt.appendChild(liJog);
});
document.body.appendChild(ulExt);
Thanks for the full reply!! Helped and learned too!
– Guilherme Lirio
Yesterday in a hurry (and with sleep) I ended up commenting some mistakes, but reading your answer I realized what I did wrong and updated my answer. Use
last
was a good "trick", in fact I need to study more jquery...– hkotsubo