Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
Vanilla javascript actualiza una tabla si se hace clic en un botón

Estoy tratando de actualizar una tabla una vez que se hace clic en un botón. He creado la tabla y el botón con el siguiente código HTML

 <button type="button" onclick="calculateMatrixFact()">Calculate MF!</button> <table id = "matrix_factorization"> <tr> <th>User</th> <th>Movie One</th> <th>Movie Two</th> </tr> </table>

Mientras que la función a la que estoy llamando en el evento onclick, es la siguiente:

 function calculateMatrixFact(){ var cache = CacheValues(); // split the array in two single arrays one per each user and movie var user_matrix = createGroups(cache.mu, 2); var score_matrix = createGroups(cache.ms, 2); // remove the string user_name and movie_name for (let i = 0; i < user_matrix.length && i < score_matrix.length; i++) { user_matrix[i].shift(); score_matrix[i].shift(); } var dot_matrix = []; // perform the dot product for (let j = 0; j < user_matrix.length; j++) { for (let k = 0; k < score_matrix.length; k++) { //console.log(user_matrix[j]) //console.log(score_matrix[k]) var dot_product = math.multiply(user_matrix[j], score_matrix[k]); dot_matrix.push(dot_product); } } // create the matrix and push back the string (first column of the table) var dot_prod_matrix = createGroups(dot_matrix, 2); dot_prod_matrix[0].unshift("Anna"); dot_prod_matrix[1].unshift("Jonny"); // from array to HTML table fetch = document.getElementById('matrix_factorization'); for (var i = 0; i < dot_prod_matrix.length; i++) { var newRow = fetch.insertRow(fetch.length); for (var j = 0; j < dot_prod_matrix[i].length; j++) { var cell = newRow.insertCell(j); cell.innerHTML = dot_prod_matrix[i][j]; } } }

Creo que el problema es que no restablezco la tabla cada vez que se hace clic en el botón, ¿no es así? ¿Cómo puedo eliminar la información anterior e insertar la nueva?

Aquí puedes ver el código completo: https://jsfiddle.net/932ebu0v/7/

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Debido a este bloque en el último de su función:

 fetch = document.getElementById('matrix_factorization'); for (var i = 0; i < dot_prod_matrix.length; i++) { var newRow = fetch.insertRow(fetch.length); for (var j = 0; j < dot_prod_matrix[i].length; j++) { var cell = newRow.insertCell(j); cell.innerHTML = dot_prod_matrix[i][j]; } }

La fetch obtendrá la tabla existente que tiene filas y usted simplemente inserta nuevas filas en ella. Luego, puede borrar toda la tabla, volver a agregar el encabezado e insertar la fila (¡el borrado y la nueva instanciación del encabezado se harían en una línea de código!):

 fetch = document.getElementById('matrix_factorization'); // Just use this line to clear whole table and put back the header row fetch.innerHTML = `<tr> <th>User</th> <th>Movie One</th> <th>Movie Two</th> </tr>`; // Put your whole <th> here. // as for the rest, just let it be for (var i = 0; i < dot_prod_matrix.length; i++) { var newRow = fetch.insertRow(fetch.length); for (var j = 0; j < dot_prod_matrix[i].length; j++) { var cell = newRow.insertCell(j); cell.innerHTML = dot_prod_matrix[i][j]; } }
about 4 years ago · Juan Pablo Isaza Denunciar

0

Una solución sencilla sería mantener la primera fila en el elemento <thead> , dado que funciona como encabezado de la tabla. El resto de las filas van dentro del elemento <tbody> . Solo el cuerpo de la tabla se restablece cada vez que se hace clic en el botón.

 // access tbody (thead remains unimpacted) var mfTableBody = document.querySelector('#matrix_factorization tbody'); mfTableBody.innerHTML = ''; // clear tbody for (var i = 0; i < dot_prod_matrix.length; i++) { // insert tr inside tbody var newRow = mfTableBody.insertRow(fetch.length); for (var j = 0; j < dot_prod_matrix[i].length; j++) { var cell = newRow.insertCell(j); cell.innerHTML = dot_prod_matrix[i][j]; } }
 <table id="matrix_factorization"> <thead> <tr> <th>User</th> <th>Movie One</th> <th>Movie Two</th> </tr> </thead> <tbody></tbody> </table>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda