如何仅使用JavaScript创建表?

时间:2019-03-13 18:20:13

标签: javascript html

以下是我仅尝试使用JavaScript复制的HTML:

<table border="1">
    <tr>
        <td>First row</td>
    </tr>
    <tr>
        <td>Second row</td>
    </tr>
    <tr>
        <td>Third row</td>
    </tr>
</table>

2 个答案:

答案 0 :(得分:3)

尝试

document.body.innerHTML=
`
<table border="1">
<tr>
    <td>First row</td>
</tr>
<tr>
    <td>Second row</td>
</tr>
<tr>
    <td>Third row</td>
</tr>
</table>
`;

答案 1 :(得分:0)

HTML代码

        <table id="table" border="2px">
            <tr id="rowid">
            </tr>
        </table>
        <br><br>
        <input type="text" placeholder="Enter column data" id="colTxt">
        <button onclick="addCol()">Add Column</button>
        <br>
        <br>
        <button onclick="addRow()">Add Row</button><br><br>
        <input type="text" placeholder="Enter Row Number" id="rowNo">
        <button id="del">Delete Row</button>

JavaScript代码

(function () {
            var del = document.getElementById("del");
            del.onclick = function () {
                deleteRow();
            }
        })();

        var tr = "";
        var addRow = function(){
            var table = document.getElementById('table');
            console.log("Tr before = "+tr);
                    tr = table.insertRow(0);
                    console.log("Tr After = "+tr);
        }
        var addCol = function () {
            var table = document.getElementById('table');
            var txt = document.getElementById('colTxt').value;
            var td = tr.insertCell(0);
            var textnode = document.createTextNode(txt);
            td.appendChild(textnode);
        }
        var deleteRow = function () {
            var table = document.getElementById('table');
            var row = parseInt(document.getElementById('rowNo').value);
            if (row>0) {
                table.deleteRow(row-1);
                alert("Row "+row+" deleted successfully");
            }
            else{
                alert("No row found")
            }
        }