Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过Javascript向表格单元格添加一些文本和输入框_Javascript_Html_Html Table_Appendchild - Fatal编程技术网

通过Javascript向表格单元格添加一些文本和输入框

通过Javascript向表格单元格添加一些文本和输入框,javascript,html,html-table,appendchild,Javascript,Html,Html Table,Appendchild,我正在尝试向HTML中预先存在的表中添加一个包含两列的行。到目前为止,我已经成功地做到了这一点。但是,我希望在每个单元格中都有文本和输入框。到目前为止,这是我最接近的一次: newinputbox = document.createElement("input"); newinputbox.setAttribute("type", "text"); table = document.getElementById("input_table"); row = table.insertRow(3);

我正在尝试向HTML中预先存在的表中添加一个包含两列的行。到目前为止,我已经成功地做到了这一点。但是,我希望在每个单元格中都有文本和输入框。到目前为止,这是我最接近的一次:

newinputbox = document.createElement("input");
newinputbox.setAttribute("type", "text");

table = document.getElementById("input_table");
row = table.insertRow(3);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
thetext = document.createTextNode("Text:");
cell1.appendChild(thetext, newinputbox);
不幸的是,这只是返回文本。如果我去掉
cell1.appendChild(thetext,newinputbox)
语句中的
thetext
,那么它只返回输入框


有人能帮我吗?

您似乎假设
appendChild()
可以接收无限数量的要追加的参数。它只期望一个;任何后续的都将被忽略

更简单的解决方案:

cell1.appendChild(newinputbox);
cell1.innerHTML += 'Text:';

问题的根源是对
Node.appendChild()
工作原理的简单误解;它只接受一个参数,并且在每个调用上只附加一个子元素

因此,修复错误的最简单方法是再次调用
Node.appendChild()

让newinputbox=document.createElement(“输入”);
setAttribute(“类型”、“文本”);
let table=document.getElementById(“输入表”),
行=表。插入行(0),
单元1=行插入单元(0),
单元2=行插入单元(1),
Text=document.createTextNode(“Text:”);
//附加第一个新的子元素:
单元格1.追加子项(文本);
//附加第二个新的子元素:
单元格1.appendChild(newinputbox)


为什么不使用cell1.innerText=“Text:
?(为输入保留
appendChild
)只接受一个参数,一次只附加一个节点。@jonatjano是的,这很有效。我不知道你能做到。谢谢你的帮助,我想在这里
innerText
会更好。另外,如果在
appendChild
之后保留对
innerHTML
的赋值,则会删除该子项,如果使用
+=
则不会。事实上,使用
innerText
,使用
=
+=
将删除其他子元素。没有看到它^^Ahhh,谢谢。我以前几乎完全做到了这一点,但我只是做了innerHTML='Text'而不是+=。我不认为appendChild(文本,newinputbox)会起作用,但这是我拥有的最好的东西。非常感谢你。