【问题标题】:JQuery: Append to table headJQuery:追加到表头
【发布时间】:2017-02-14 02:23:56
【问题描述】:

所以我试图将数据从 Url 附加到表的头部。从 URL 调用的数据是一个字符串列表。如您所见,我正在尝试遍历列表中的每个值,然后将其附加到我的表头“数据”中。 但是当我运行代码时,没有附加任何内容。我知道数据正在输入,因为窗口警报正在显示每个字符串。

JQuery:

$(document).ready(function () {
    $.ajax({
        url: 'http://..../api/Dynamic?table=table1',
        dataType: 'Json',
        success: function (tableResults) {
            var count = 0;
            $.each(tableResults, function () {
                window.alert(this);
                $('#data th:last-child').append('<th><a id="count">' + this + '</a></th>');
                count++;
            });
        }
    });
});

HTML:

<table id="data" border="1" align="center" width="95%">
        <thead>
            <tr>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

有什么建议吗?

【问题讨论】:

  • 你...将一个 th 附加到一个 th 上。这没有意义。

标签: jquery ajax append html-table head


【解决方案1】:

如果 tableResults 是一个字符串数组,您可以直接使用每个参数并避免像下面的 sn-p 中的 count 变量(使用 after 而不是 append 因为新的 th 元素必须跟随而不是最后的子元素th):

//
// if thead does not exist
//
if ($('#data thead').length == 0) {
  $('#data').append($('<thead/>'));
}

$.each(['email', 'address', 'country'], function (index, value) {
  if ($('#data th:last-child').length == 0) {
     //
     // if there are no th
     //
    $('#data thead').append('<th><a id="count' + index + '"</a>' + value + '</th>');
  } else {
    $('#data th:last-child').after('<th><a id="count' + index + '"</a>' + value + '</th>');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table id="data" border="1" align="center" width="95%">
  <thead>
    <tr>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

【讨论】:

  • 表头为空怎么办?
  • 是的,它与您的数组类似,我没有收到错误
  • @JacksonSentzke 我的 sn-p 工作吗?我更新了它。你能再测试一次并告诉我吗?谢谢
  • 我认为$('#data thead tr').append(...) 足以涵盖这两种情况(无论thead 是否为空),不需要if 声明。
  • @Artur Filipiak 你是对的。问题与评论有关:如果 thead 或 th 没有退出,我该如何创建它们?我理解你的观点,但我的回答是基于如果元素不存在,你如何创建它。现在看问题和答案显然是多余的……无论如何,非常感谢。
猜你喜欢
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-07
  • 1970-01-01
  • 1970-01-01
  • 2011-04-04
  • 2018-10-06
相关资源
最近更新 更多