Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Cómo almacenar la salida de la función en el elemento <tr></tr>

Estoy trabajando en un proyecto simple de seguimiento de gastos. Necesito almacenar la salida de createAlltd() en un elemento nuevo cada vez que hago clic en btn y lo adjunto al elemento. Hasta ahora solo logré almacenar todos los td en tbody pero sin el elemento tr y viceversa.

 const exp = document.querySelector('.addExpense'); //tbody const expInp = document.querySelector('.expense'); const dateInp = document.querySelector('.date'); const amountInp = document.querySelector('.amount'); const btn = document.querySelector('.btn'); function createTd(e){ var td = document.createElement('td');; td.innerText = e.value; e.value = ""; } function createTr(){ var newTr = document.createElement('tr'); newTr.className = ".newTr"; exp.append(newTr); } function createAllTd(){ createTd(expInp); createTd(dateInp); createTd(amountInp); } btn.addEventListener('click', (e) => { e.preventDefault(); createTr(); createAllTd(); expInp.focus(); });
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Entonces, lo que debe hacer es buscar de alguna manera la fila que ha creado y luego agregar las columnas a esa fila.

Por lo tanto, podemos cambiar la función createTr() para devolver la fila recién agregada obteniendo el último elemento dentro de <tbody> . Por lo tanto, la función ahora se vería así:

 function createTr(){ var newTr = document.createElement('tr'); newTr.className = ".newTr"; exp.append(newTr); return newTr; }

ahora que tenemos acceso a la fila recién creada a través del código, podemos pasar esto a nuestra función createAllTd() y desde allí a createTd() y agregar <td> al elemento <tr> como ahora está disponible. Por lo tanto, las funciones ahora se ven así:

 function createTd(e, elNewTr){ var td = document.createElement('td');; td.innerText = e.value; e.value = ""; // This statement appends the TD inside the TR as passed in the parameter elNewTr.append(td); } function createAllTd(elNewTr){ // Pass the newly created TR element to the TD functions so that we can append TD inside the new TR createTd(expInp, elNewTr); createTd(dateInp, elNewTr); createTd(amountInp, elNewTr); }

Por lo tanto, el código final ahora se ve así:

 const exp = document.querySelector('.addExpense'); //tbody const expInp = document.querySelector('.expense'); const dateInp = document.querySelector('.date'); const amountInp = document.querySelector('.amount'); const btn = document.querySelector('.btn'); function createTd(e, elNewTr){ var td = document.createElement('td');; td.innerText = e.value; e.value = ""; // This statement appends the TD inside the TR as passed in the parameter elNewTr.append(td); } function createTr(){ var newTr = document.createElement('tr'); newTr.className = ".newTr"; exp.append(newTr); return newTr; } function createAllTd(elNewTr){ // Pass the newly created TR element to the TD functions so that we can append TD inside the new TR createTd(expInp, elNewTr); createTd(dateInp, elNewTr); createTd(amountInp, elNewTr); } btn.addEventListener('click', (e) => { e.preventDefault(); // Catch the new TR element as returned elNewTr = createTr(); // Pass it to the TD creation process for usage createAllTd(elNewTr); expInp.focus(); });

Esto debería hacerlo.

about 4 years ago · Juan Pablo Isaza Report

0

Su problema es que crea elementos separados de tr y td pero no agrega los td a tr relevante. Use la función .appendChild() para esto, como:

 tr.appendChild(td);

Actualicé su código, ver más abajo. Preste atención: las funciones para crear filas y celdas ahora tienen valores de retorno. Y el detector de eventos usa esos valores para agregar las celdas a la fila.

Desafortunadamente, no puedo probar la solución debido a la falta de HTML y datos en la pregunta.

 const exp = document.querySelector('.addExpense'); //tbody const expInp = document.querySelector('.expense'); const dateInp = document.querySelector('.date'); const amountInp = document.querySelector('.amount'); const btn = document.querySelector('.btn'); function createTd(e){ var td = document.createElement('td');; td.innerText = e.value; e.value = ""; } function createTr(){ var newTr = document.createElement('tr'); newTr.className = ".newTr"; exp.append(newTr); return newTr; } function createAllTd(){ let tds = []; tds.push(createTd(expInp)); tds.push(reateTd(dateInp)); tds.push(createTd(amountInp)); return tds; } btn.addEventListener('click', (e) => { e.preventDefault(); let row = createTr(); let cells = createAllTd(); cells.forEach(cell => { row.appendChild(cell); }) expInp.focus(); });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!