javascript 如何在表格单元格中插入输入字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8402067/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:19:59  来源:igfitidea点击:

How insert an input field in a table cell?

javascript

提问by Crayl

Sorry for the noob question: I want to create a table with input fields where the can add new ones, if they are needed. But I can'T figure out how add another input field inside a cell where another input field already exists.

对于菜鸟问题​​很抱歉:我想创建一个带有输入字段的表,如果需要,可以在其中添加新字段。但我无法弄清楚如何在另一个输入字段已经存在的单元格中添加另一个输入字段。

My code is:

我的代码是:

var par=obj.parentNode;
while(par.nodeName.toLowerCase()!='tr')
{ par=par.parentNode; }
// this gives me the index of the row.. works fine.

cell1=document.getElementById('avz_tabelle').rows[par.rowIndex].cells;
// this puts the content of the cells into the array "cell1"

var feld = cell1[1].createElement("input"); 
feld.setAttribute("name","avz_keywords" + avz_array + "[]"); 
feld.setAttribute("onblur","");
feld.setAttribute("type","text"); 
feld.setAttribute("size","30"); 
// Now I create a input element
// And now comes the problem:

cell1[1].appendChild(feld); // --> doesn't work

Has anyone a suggestion for me? I got the idea to work without a table, theoratically that would work with my way. But that wouldn't be satisfying :/

有人给我建议吗?我想到了不用桌子也能工作的想法,理论上这符合我的方式。但这不会令人满意:/

回答by Michael Berkowski

If you look in a debugging console, you should see something like

如果您查看调试控制台,您应该会看到类似

TypeError: Object #<HTMLDivElement> has no method 'createElement'

Instead of creating the element from cell1[1], use document.createElement()

而不是从创建元素cell1[1],使用document.createElement()

 var feld = document.createElement("input");

回答by codeling

You should use document.createElement("input");instead of cell1[1].createElement("input");

你应该使用document.createElement("input");而不是cell1[1].createElement("input");

As always (and as also stated in another answer here), the JavaScript console should be the first place to look for hints on what the problem is!

与往常一样(也如此处的另一个答案中所述),JavaScript 控制台应该是第一个寻找问题提示的地方!

And wouldn't it actually be much easier if each table cell you want to add values to got a separate ID? Something containing perhaps the row index and the column index ... Then you could just select it directly.

如果您想为每个表格单元格添加值以获得单独的 ID,实际上不是更容易吗?可能包含行索引和列索引的东西......然后你可以直接选择它。