【问题标题】:How to Add data in tbody using Javascript only如何仅使用 Javascript 在 tbody 中添加数据
【发布时间】:2016-10-10 12:17:51
【问题描述】:

这是我的 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 运行时错误:层次结构请求错误

【问题讨论】:

  • 您需要将元素传递给appendChild() 而不是字符串。 (先用document.createElement("tr")创建一个,更新,追加)
  • 您实际上必须使用 JS 创建元素。您不能像使用 jQuery 那样只附加一个字符串。 w3schools.com/js/js_htmldom_nodes.asp
  • @Gavin w3fools.com
  • 你好先生,你能给我看一个例子吗@Alex k
  • 您可以使用 .innerHTML = row 而不是 .appendChild(row)。不过,这将替换整个表体。如果你之后想要附加一些东西,你必须先获取 innerHTML 并将你的字符串附加到那个,然后再执行 .innerHTML = row.

标签: javascript html dom-events


【解决方案1】:

使用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;
}

【讨论】:

    【解决方案2】:

    这里有一个fiddle。让我们知道它是否对您有所帮助。
    基本上,您可以使用 .innerHTML 将字符串作为元素附加,因为这会“由浏览器评估”。

    否则,您必须以编程方式进行cmets中提到

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-11
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      • 2011-10-06
      • 2016-04-27
      • 1970-01-01
      • 2012-09-28
      相关资源
      最近更新 更多