javascript 如何使用js向td添加按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15315315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I add a button to a td using js?
提问by iCodeLikeImDrunk
I have a table that is generated on the fly, as it is generating its TDs, I want to set the first TD to be a button. Below is my code, obviously doesn't work. I remember from another problem I had that we can change the content of a div using the .html(), but that doesnt work here neither.
我有一个动态生成的表,因为它正在生成它的 TD,我想将第一个 TD 设置为一个按钮。下面是我的代码,显然不起作用。我记得我遇到的另一个问题是我们可以使用 .html() 更改 div 的内容,但这在这里也不起作用。
Code:
代码:
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;
}
回答by Niet the Dark Absol
You can either use td.innerHTML = '<input type="button"...';
or you can do it the "proper" way:
您可以使用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);
回答by Miguel Alonso Mosquera
This works for me.
这对我有用。
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>";