首页 > 解决方案 > 如何将子表附加到我的单元格和行

问题描述

您好,我的代码有问题。我不知道该怎么做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')))

标签: javascript

解决方案


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>元素。现在该行被放置在正确的位置。


推荐阅读