使用 javascript 将文本字段插入 table 单元格

inserting text-field to table cell using javascript

我正在编写一个程序,我想在其中向 table 单元格添加一个输入字段。 看下面的代码:

var arr_title = ["song","artist","genre"];
for (var title in arr_title){
    var newl = document.createElement("input");
    newl.id = 'edit_text';
    var  newf = "td_" + arr_title[title];
    newf.appendChild(newl);
}

newf 获取 td_song、td_artist 等的值,这些已经定义为:

var td_song = document.createElement("td");
var td_artist = document.createElement("td");
var td_genre = document.createElement("td");

在同一个函数中,然后我将它们附加到 table 并且它工作正常

但是当我创建输入元素时出现错误:

未捕获类型错误:newf.appendChild 不是函数

我知道它没有结束标签,它需要在一个表单元素中,但是当我尝试添加任何其他元素时,错误是一样的。

求助!

您要添加的 <td> 的 ID 是否为 "td_" + arr_title[title]? 如果是这样,你需要做...

var newf = document.getElementById("td_" + arr_title[title]);
newf.appendChild(newl);

newf 是一个字符串,你不能将子项附加到字符串,如果你想引用这个名称的变量,你应该使用 window :

window[newf].appendChild(newl);

希望对您有所帮助。

存储在newf中的值是一个字符串,而不是DOM元素; appendChild 不是字符串的有效方法。仅仅因为 newf 中存储的字符串值与您创建的变量名称(td_song 等)匹配,并不意味着它现在是该元素的句柄。您最好将创建的元素存储在一个对象中,以该值作为键:

var elems = {
  td_song: document.createElement("td"),
  td_artist: document.createElement("td"),
  td_genre: document.createElement("td")
};
var arr_title = ["song","artist","genre"];
for (var title in arr_title){
    var newl = document.createElement("input");
    newl.id = 'edit_text';
    var  newf = "td_" + arr_title[title];
    elems[newf].appendChild(newl);
}

在这一行之后,newf 的内容只是一个字符串,例如 "td_song"。

var  newf = "td_" + arr_title[title];

您可能遇到 "newf is not a function" 的 JS 错误?

如果您想让 newf 真正成为这些变量之一,您可以探索使用 eval()

var  newf = eval("td_" + arr_title[title]);