我如何动态地添加一个输入字段到一个单元格内我的html表行在javascript?



这是我的代码:

var tab=document.getElementById("quarter_details");
var input = document.createElement("input");
input.type = "text";
input.placeholder = "dd/mm/yyyy";
input.id = "vac";
var row = tab.insertRow(5);
var cell = row.insertCell(0);
var cell1 = row.insertCell(1);
cell.innerHTML = "<b>Date:</b>";
cell1.innerHTML = input; //[object HTMLInputElement]

当我运行代码时,输入文本字段没有出现。我该怎么办?

编辑:尝试使用cell1.appendChild = input。现在它显示了一个空单元格,没有输入字段

使用appendChild方法:

cell1.appendChild(input);

使用insertAdjacentHTML。下面是一个最小的可复制示例。

const createDateTimeInput = (forCell, id) => {
forCell.textContent = ``; // empty the cell
forCell.insertAdjacentHTML(
`beforeend`, 
`<b>Date</b> <input type="text" placeholder="dd/mm/yyyy" id="${id}">`);
};
const firstCellOfSecondRow = 
document.querySelector(`table tbody tr:nth-child(2) > td`);
setTimeout(() => createDateTimeInput(firstCellOfSecondRow, `vac`), 2000);
thead th {
text-align: left
}
<table>
<thead>
<tr>
<th>first column</th>
<th>second column</th>
</tr>
</thead>
<tbody>
<tr>
<td>cell</td>
<td>cell</td>
</tr>
<tr>
<td>cell</td>
<td>cell</td>
</tr>
</tbody>
</table>

最新更新