JQuery:追加到 table 头部
JQuery: Append to table head
所以我试图将数据从 Url 附加到 table 的头部。从 URL 调用的数据是一个字符串列表。因此,正如您所看到的,我正在尝试遍历列表中的每个值,然后将其附加到我的 table、'data' 的头部。
但是当我 运行 代码时,没有附加任何内容。我知道数据正在进入,因为 window 警报正在显示每个字符串。
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>
有什么建议吗?
如果 tableResults 是一个字符串数组,您可以直接使用每个参数并避免使用 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>
所以我试图将数据从 Url 附加到 table 的头部。从 URL 调用的数据是一个字符串列表。因此,正如您所看到的,我正在尝试遍历列表中的每个值,然后将其附加到我的 table、'data' 的头部。 但是当我 运行 代码时,没有附加任何内容。我知道数据正在进入,因为 window 警报正在显示每个字符串。
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>
有什么建议吗?
如果 tableResults 是一个字符串数组,您可以直接使用每个参数并避免使用 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>