如何仅使用Javascript在主体中添加数据

How to Add data in tbody using Javascript only

本文关键字:添加 数据 主体 何仅使 Javascript      更新时间:2023-09-26

这是我的Javascript函数

function SaveCustomdata() {
    var customName = document.getElementById("lblNAME").value;
    var customEmail = document.getElementById("lblEmail").value;
    var customContectNo = document.getElementById("lblContectNO").value;

    var row = "";
    row += '<tr><td>' + customName + '</td><td>' + customEmail + '</td><td>' + customContectNo + '</td></tr>';
    document.getElementById("Customdata").appendChild(row);
}
            

附加数据的HTML代码:

<table>
    <thead>
        <tr>
            <th style=" color:#01A0DF; padding-right:60px;">Name</th>
            <th style=" color:#01A0DF; padding-right:70px;">Email</th>
            <th style=" color:#01A0DF; padding-right:90px;">Contect/Mobile No</th>
            <td>
                <input type="button" id="btnclick" value="Add" onclick="AddRecord()" />
            </td>
        </tr>
    </thead>
    <tbody id="Customdata"></tbody>
</table>
                        

出现错误:

0x800a139e - JavaScript运行时错误:Hierarchy Request error

使用innerHTML:

function SaveCustomdata() {
    var customName = document.getElementById("lblNAME").value;
    var customEmail = document.getElementById("lblEmail").value;
    var customContectNo = document.getElementById("lblContectNO").value;
    var row = "";
    row += '<tr><td>' + customName + '</td><td>' + customEmail + '</td><td>' + customContectNo + '</td></tr>';
    // get the current table body html as a string, and append the new row
    var html = document.getElementById("Customdata").innerHTML + row;
    // set the table body to the new html code
    document.getElementById("Customdata").innerHTML = html;
}

给你一把小提琴。如果它对你有帮助,请告诉我们。
基本上你可以使用.innerHTML附加字符串作为元素,因为这得到"由浏览器评估"。

否则就必须按照注释

中提到的编程方式来做了。