javascript 使用 AJAX 的数据表中的子行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30127285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Child rows in DataTables using AJAX
提问by user2281858
I am trying to bind a child table with a parent table. I am not able to figure out how this can be done when the data for the child table is coming through an AJAX call which then creates a dynamic table.
我正在尝试将子表与父表绑定。当子表的数据通过 AJAX 调用传入时,我无法弄清楚如何做到这一点,然后创建一个动态表。
I have followed this
我遵循了这个
Below is my code.
下面是我的代码。
$('#myTable tbody).on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = $('#myTable').DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child(format()).show();
tr.addClass('shown');
}
});
function format() {
$.ajax({
type: 'GET',
url: '@Url.Action("MyFunction", "Home")',
data: { "Id": MyId },
dataType: "json",
async: false,
success: function (data) {
var list = data;
$.each(list, function (index, item) {
return '<table>.......<table />';
//i need to loop across the list and create a dynamic table with tr and td
});
},
error: function (result) {
var error = JSON.stringify(result);
throw "Error...";
}
});
}
采纳答案by Ja9ad335h
$('#myTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = $('#myTable').DataTable().row(tr);
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
format(row.child); // create new if not exist
tr.addClass('shown');
}
});
and then the format()
will be
然后format()
将是
function format(callback) {
$.ajax({
....
//async: false, you can use async
success: function (data) {
var list = data;
var html = '';
$.each(list, function (index, item) {
...
//create <tr> <td> with loop
html= '<tr><td>.......</tr>';
});
callback($('<table>' + html + '</table>')).show();
},
...
});
}
demo here jsfiddle
在这里演示jsfiddle