如何使用js向td添加按钮?

时间:2013-03-09 20:04:49

标签: javascript button

我有一个动态生成的表,因为它正在生成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;
    }

2 个答案:

答案 0 :(得分:12)

您可以使用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);

答案 1 :(得分:0)

这对我有用。

 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>";