Vanilla javascript 在单击按钮时更新 table

Vanilla javascript update a table if a button is clicked

我正在尝试在单击按钮后更新 table。我使用以下 HTML 代码

创建了 table 和按钮
<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>

我在 onclick 事件上调用的函数如下:

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];
    }
    }
}

我认为问题在于每次单击按钮时我都没有重置 table,对吗?如何删除旧信息并插入新信息?

在这里你可以看到完整的代码:https://jsfiddle.net/932ebu0v/7/

因为这个块在你的函数的最后:

    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];
    }
    }

fetch 将获取现有的 table 行,您只需将新行插入其中。 然后,您可以清除整个 table、re-add 和 header 并插入行(header 的清除和 re-instantiation 将在一行中完成代码!!):

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];
    }
    }