Dolgozók renderelése szerkesztő és nyomógombbal.
<table class="table table-striped"> <thead> <tr> <th>id</th> <th>Név</th> <th>Település</th> <th>Fizetés</th> </tr> </thead> <tbody id="empsBody"></tbody> </table>
function renderTable() { state.empList.forEach(emp => { let tr = document.createElement('tr'); tr.innerHTML =` <td>${emp.id}</td> <td>${emp.name}</td> <td>${emp.city}</td> <td>${emp.salary}</td> <td> <button class="btn btn-primary" data-id="${emp.id}" data-name="${emp.name}" data-city="${emp.city}" data-salary="${emp.salary}" onclick="updateEmployee(this)" >Szerkesztés</button> <button class="btn btn-primary" onclick="deleteEmployee(${emp.id})" >Törlés</button> </td> `; doc.empsBody.appendChild(tr); }); } function updateEmployee(source) { console.log(source.dataset.city) } function deleteEmployee(id) { console.log(id) }
onclick="updateEmployee()"
function updateEmployee() { const source = this.event.target; console.log(source.dataset.city) }
onclick="updateEmployee()"
function updateEmployee() { const source = this.event.target; console.log(source.getAttribute('data-city')) }
<!-- ... --> <table class="table table-striped"> <thead> <tr> <th>Id</th> <th>Név</th> <th>Település</th> <th>Fizetés</th> </tr> </thead> <tbody id="empsBody"></tbody> </table> </div> <script type="module" src="app.js"></script> <!-- ... -->
const url = 'http://localhost:8000/employees'; async function getEmployees() { try { let response = await fetch(url); let result = await response.json(); return result; }catch (err) { console.log('Hiba! A dolgozók lekérése sikertelen!'); console.log(err); } } export { getEmployees }
import { getEmployees } from "./apiService.js"; const doc = { empsBody: document.querySelector('#empsBody') } const state = { empList: [] } window.addEventListener('load', () => { init(); }); function init() { getEmps(); } async function getEmps() { state.empList = await getEmployees(); renderTable() } function renderTable() { state.empList.forEach(emp => { let tr = document.createElement('tr'); tr.innerHTML =` <td>${emp.id}</td> <td>${emp.name}</td> <td>${emp.city}</td> <td>${emp.salary}</td> <td> <button class="btn btn-primary" data-id="${emp.id}" data-name="${emp.name}" data-city="${emp.city}" data-salary="${emp.salary}" >Szerkesztés</button> <button class="btn btn-primary" >Törlés</button> </td> `; const editBtn = tr.querySelector('button:nth-child(1)'); editBtn.addEventListener('click', () => updateEmployee(editBtn)); const delBtn = tr.querySelector('button:nth-child(2)'); delBtn.addEventListener('click', () => deleteEmployee(emp.id)); doc.empsBody.appendChild(tr); }); } function updateEmployee(source) { console.log(source.dataset.city) } function deleteEmployee(id) { console.log(id) }