Hej, mam problem z kolejnym zadaniem. Mianowicie: na stronie mam 3 linki ("Mężczyźni, Kobiety, Wszyscy"). Po kliknięciu na dany link uzupełniam tabelę ("Imię, nazwisko, płeć, zdjęcie"). Danę muszę wziąć z linku JSON. Jako płeć też musi mi się wyświetlać obrazek. Wiem jak zrobić, żeby się wyświetlali "wszyscy", ale mam problem z "podziałem" na mężczyzn i kobiety. Jak również mam problem, żeby wyświetlić zdjęcie z JSON w mojej tabeli.
HTML:
<body>
<a href="#" id="mannen">Mannen</a>
<a href="#" id="vrouwen">Vrouwen</a>
<a href="#" id="allen">Allen</a>
<table>
<thead>
<tr>
<th>Voornaam</th>
<th>Familienaam</th>
<th>Geslacht</th>
<th>Foto</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id="nietGevonden" hidden class="fout">Niet gevonden.</div>
</body>
Javascript:
const allen = document.getElementById("allen");
const man = document.getElementById("mannen");
const vrouw = document.getElementById("vrouwen");
allen.onclick = function (){
leesGeslachten();
}
man.onclick = function () {
leesGeslachten()
}
async function leesGeslachten () {
const response = await fetch("geslachten.json");
if (response.ok) {
const geslachten = await response.json();
verwerkGeslachten(geslachten);
} else {
document.getElementById("nietGevonden").hidden = false;
}
}
function verwerkGeslachten(geslachten) {
const tbody = document.querySelector("tbody");
verwijderAlleChildElementenVan(tbody);
for (const geslacht of geslachten) {
voegPersoonToe(tbody, geslacht, man);
}
}
function voegPersoonToe(tbody, geslacht) {
const tr = tbody.insertRow();
const tdVoornaam = tr.insertCell();
tdVoornaam.innerText = geslacht.voornaam;
const tdFamilienaam = tr.insertCell();
tdFamilienaam.innerText = geslacht.familienaam;
const tdGeslacht = tr.insertCell();
tdGeslacht.innerHTML = <img src='man.png'>;
const tdFoto = tr.insertCell();
tdFoto.innerHTML = geslacht.foto;
}
function verwijderAlleChildElementenVan (element) {
while (element.lastChild !== null) {
element.lastChild.remove();
}
}
JSON (przykładowe):
{
"voornaam": "Noah",
"familienaam": "Smith",
"geslacht": "man",
"foto": "man1.jpg"
},
{
"voornaam": "Emma",
"familienaam": "Johnson",
"geslacht": "vrouw",
"foto": "vrouw1.jpg"
},
Przepraszam, że po holendersku, mam nadzieję, że to nie problem :). Obrazki do płci to odpowiednio "man.png" i "vrouw.png" . Podejrzewam, że muszę tu wykorzystać ("if else"), ale na razie mam z tym problem :).