javascript - 将新数据从 JSON 添加到现有表

标签 javascript jquery html json html-table

我正在尝试将新数据(来自 JSON)添加到现有表(使用 jquery)。

例如,在我的 html 中有这个表格:

<table data-role="table" data-mode="columntoggle" class="ui-responsive" data-column-btn-text="Filter Columns" id="MyTable">
  <thead>
    <tr>
      <th data-priority="1">A</th>
      <th data-priority="2">B</th>
      <th data-priority="3">C</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>a1</td>
      <td>b1</td>
      <td>c1</td>
    </tr>
  </tbody>
  </table>

我正在尝试这样做(从 JSON 添加新数据):

var response = [{
      "A":"a2",
      "B":"b2",
      "C":"c2"
     },
     {
      "A":"a3",
      "B":"b3",
      "C":"c3"
    },
    {
      "A":"a4",
      "B":"b4",
      "C":"c4"
    }];

    $.each(response, function(i, item) {
                $('<tr>').html(
                //"<tr>" +
                "<td>" + response[i].A + "</td><td>" + response[i].B + "</td><td>" + response[i].C + "</td>" + "</tr>").appendTo('#MyTable');
        });

为什么它不起作用?

最佳答案

您将内容附加到表格本身,而不是 theadtbody 元素,这是应该做的。尝试将 .appendTo 中的选择器更改为 #MyTable tbody,它将起作用。 Demo here.

关于javascript - 将新数据从 JSON 添加到现有表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23501497/

相关文章:

javascript - Canvas 动画未按预期工作

javascript - 如何查看字段在 mongodb 中按字母顺序变化的时间?

javascript - 当表单项未回复时如何发出警报?

javascript - 如何获取数组中每个id的最小值

javascript - 正文溢出:visible on pop up close

html - 文本突出显示在顶部被切断

html - HTML 文档或 CSS 树的深度是否有限制?

jquery - PC 浏览器上的性能无限滚动

javascript - jQuery:如何正确暂停递归?

javascript - 使用带有 switch 语句的 jQuery 显示某些按钮