javascript - 如何将子表附加到我的单元格和行
问题描述
您好,我的代码有问题。我不知道该怎么做table.appendchild(row)
。我尝试用 append 或 appendchild 来做,但没有用。
我的代码:
var body = document.getElementsByTagName('body')[0];
var table = document.createElement('table');
body.appendChild(table);
var createrow = function(c1,c2){
var row = document.createElement('tr');
row.appendChild(c1);
row.setAttribute('class', 'row')
row.appendChild(c2);
return row;
}
var createcell = function(value){
var cell = document.createElement('td');
cell.setAttribute('class', 'cell');
cell.innerText=value;
table.appendChild(cell);
return cell;
}
body.appendChild(createrow(createcell('Ion'),createcell('24')))
body.appendChild(createrow(createcell('Gigle'),createcell('26')))
解决方案
target.appendChild(another)
意思是“把这个元素“另一个”放在元素“目标”中作为子元素。
您在代码中犯了一些错误。第一个是你的createcell
功能:
var createcell = function(value){
var cell = document.createElement('td');
cell.setAttribute('class', 'cell');
cell.innerText=value;
// table.appendChild(cell); -- uncommented
return cell;
}
此函数的目的是为您的表格创建一个“单元格”。您正在这样做,但您也在这样做table.appendChild(cell);
,这意味着您将该单元格放在表格中。这是不正确的。我已取消注释。
你createrow
的功能似乎是正确的。
最后,你在做
body.appendChild(createrow(createcell('Ion'),createcell('24')))
这意味着“获取createrow
函数的结果(这是您的<tr>
元素)并将其放入元素“body”中。你body
是<body>
元素。不是你想给你的东西。您想将该行放在表中。因此,您需要将其更正为
table.appendChild(createrow(createcell('Ion'),createcell('24')))
这意味着“创建一行,并将其作为子元素放置在元素“table”中”。你table
的就是<table>
元素。现在该行被放置在正确的位置。
推荐阅读
- java - Chronicle Queue 使用零分配从队列读取/写入
- java - 当我选择图像时它不会出现
- javascript - 如何在 chrome 扩展中保存值?
- objective-c - 检查所有相关的 Xcode 设置后,我的可执行文件仍然显示“已通过优化编译”。有什么建议吗?
- amazon-web-services - 将 AWS cli 命令与 xargs 结合使用不起作用
- javascript - express PUT 请求超时
- php - 一个苗条的应用程序可以存在于其他应用程序(使用其他框架)已经在工作的网络服务器中吗?
- python - Flask_User 和 Blueprint - 如何构建应用程序?
- java - 发送电子邮件后如何将用户发送到另一个活动
- linux - 即使在授予完全权限后也无法执行文件(在 linux 中)