首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Javascript动态建表

使用Javascript动态建表
EN

Stack Overflow用户
提问于 2011-04-08 14:53:25
回答 1查看 1.9K关注 0票数 1

我需要使用JavaScript在按钮单击事件上向表中动态添加行。此外,表单元格还需要包含文本框。

我该怎么做呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-04-08 14:59:42

下面是取自此source的示例代码。建议你阅读更多关于DOM的知识,特别是关于这个问题的DOM tables

代码语言:javascript
复制
function start() {
    // get the reference for the body
    var body = document.getElementsByTagName("body")[0];

    // creates a <table> element and a <tbody> element
    var tbl     = document.createElement("table");
    var tblBody = document.createElement("tbody");

    // creating all cells
    for (var j = 0; j < 2; j++) {
        // creates a table row
        var row = document.createElement("tr");

        for (var i = 0; i < 2; i++) {
            // Create a <td> element and a text node, make the text
            // node the contents of the <td>, and put the <td> at
            // the end of the table row
            var cell = document.createElement("td");
            var cellText = document.createTextNode("cell is row "+j+", column "+i);
            cell.appendChild(cellText);
            row.appendChild(cell);
        }

        // add the row to the end of the table body
        tblBody.appendChild(row);
    }

    // put the <tbody> in the <table>
    tbl.appendChild(tblBody);
    // appends <table> into <body>
    body.appendChild(tbl);
    // sets the border attribute of tbl to 2;
    tbl.setAttribute("border", "2");
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5591507

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档