简体   繁体   English

动态地向表中添加行

[英]Dynamically adding rows to a table

I'm trying to dynamically add a <tr> with two <td> s into a <table> via javascript, but my fiddle doesn't seem to do anything, does anyone see the problem? 我试图通过javascript动态地将带有两个<td><tr>添加到<table> ,但是我的小提琴似乎没有做任何事情,是否有人看到了这个问题?

Fiddle: https://jsfiddle.net/otL69Lpo/2/ 小提琴: https//jsfiddle.net/otL69Lpo/2/

HTML: HTML:

<button type="button" onclick="myFunction()">Click Me!</button>

<table class="table table-bordered" id="chatHistoryTable">
  <tr>
    <td>
      12:30:30
    </td>
    <td>
      text here
    </td>
</table>

JS: JS:

function myFunction() {
  var table = document.getElementById("chatHistoryTable");

  var tr = document.createElement("tr");
  var td = document.createElement("td");
  var td2 = document.createElement("td");
  var txt = document.createTextNode("TIMESTAMP");
  var txt2 = document.createTextNode("user: text");

  td.appendChild(txt);
  td2.appendChild(txt2);
  tr.appendChild(td);
  tr.appendChild(td2);
  table.appendChild(tr);
}

Output should be as: 输出应为:

| TIMESTAMP | user: text |

This is a common issue in jsFiddle. 这是jsFiddle中的常见问题。 There are several options for how to load the JS and you'll need to change the loading to either: 有几种方法可以加载JS,你需要将加载更改为:

  • No wrap - in <head>
  • No wrap - in <body>

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM