首页 > 解决方案 > a ForEach function to make one tr to three tds and make a dinamic table

问题描述

I need to make a little site that get some text boxes, ('Codigo' 'Nome' 'Documento') put on a array, that I already did, and make a a function with ForEach to create only one <tr> to three <td> I'm just not understand what I'm doing bad

function atualizarTabela() {
    var tabelaBody = document.getElementById("corpo-tabela"); // corpo-tabela = tbody I need to clean it first

    tabelaBody.innerHTML = "";

    registros.forEach(function (registros) {  // registros is my array that content the three text boxes
        var createTr = document.createElement('tr');
        for (var i = 0; i < registros[i]; i++) {
            var createTd = document.createElement("td");
            createTd.textContent = registro[i];
            createTr.appendChild(createTd);
        }
    });
};
<body>

    <table id="clientes">
        <thead>
            <tr>
                <th>Codigo</th>
                <th>Nome</th>
                <th>Documento</th>
            </tr>
        </thead>
        <tbody id="corpo-tabela">
        </tbody>
    </table>
<div id="bloco-dados">
        <p>Código</p>
        <input type="text" id="txtCodigo" name="Código">
        <p>Nome</p>
        <input type="text" id="txtNome" name="Nome">
        <p>Documento</p>
        <input type="text" id="txtDocumento" name="Documento"><br>
        <input type="button" name="botao" id="btnSalvar" value="Salvar"><br>
        <input type="button" name="botao2" id="btnNovo" value="Novo">
    </div>


    <script src="script.js" type="text/javascript"></script>
</body>

Thank you :)

标签: javascripthtml

解决方案


Try removing the white space between function and the argument, and changing the argument to a dummy variable. So

registros.forEach(function(r) {
  var createTr = document.createElement('tr');
  for (var i = 0; i < r.length; i++) {
    let createTd = document.createElement("td");
    createTd.textContent = r[i];
    createTr.appendChild(createTd);
    tabelaBody.appendChild(createTr);
  }
});

推荐阅读