5

我有一个动态生成的表,因为它正在生成它的 TD,我想将第一个 TD 设置为一个按钮。下面是我的代码,显然不起作用。我记得我遇到的另一个问题是,我们可以使用 .html() 更改 div 的内容,但这在这里也不起作用。

代码:

    var table = document.getElementById("userinfo");
    var thead, tr, td;
    table.appendChild(thead = document.createElement("thead"));
    thead.appendChild(tr = document.createElement("tr"));
    tr.appendChild(td = document.createElement("td"));
    td.innerHTML = "Email";
    tr.appendChild(td = document.createElement("td"));
    td.innerHTML = "First Name";
    tr.appendChild(td = document.createElement("td"));
    td.innerHTML = "Last Name";
    tr.appendChild(td = document.createElement("td"));
    td.innerHTML = "Is Active?";

    for (var i in data)
    {
        tr = document.createElement("tr");
        tr.setAttribute("id", "row" + i);
        if (i%2 == 0)
        {
            tr.setAttribute("style", "background:white");
        }

        var entry = data[i];
        console.log(entry);
        table.appendChild(tr);
        tr.appendChild(td = document.createElement("td"));
        td.setAttribute("html", "<input type=\"button\" class=\"btn\" value=\'" + entry.email + "\" onclick=\"" + chooseUser(entry) + "\"/>");
        tr.appendChild(td = document.createElement("td"));
        td.innerHTML = entry.first_name;
        tr.appendChild(td = document.createElement("td"));
        td.innerHTML = entry.last_name;
        tr.appendChild(td = document.createElement("td"));
        td.innerHTML = entry.isActive;
    }
4

2 回答 2

19

您可以使用td.innerHTML = '<input type="button"...';,也可以以“正确”的方式进行:

var btn = document.createElement('input');
btn.type = "button";
btn.className = "btn";
btn.value = entry.email;
btn.onclick = (function(entry) {return function() {chooseUser(entry);}})(entry);
td.appendChild(btn);
于 2013-03-09T20:08:58.487 回答
1

这对我有用。

 var row = {};
     var myTable = document.querySelector("table#tableProducts>tbody");

     row = myTable.insertRow();

     row.insertCell(-1).textContent = "dummy";
     var lastRow = row;
     var lastCell = lastRow.cells[lastRow.cells.length - 1];
     lastCell.innerHTML = "<button id='btnEdit';>Editar</button>";
于 2019-11-28T21:30:54.307 回答