【发布时间】:2020-07-27 07:45:43
【问题描述】:
我有一个关于 jquery 数据表的小问题。我正在尝试制作表格,当我单击一行时,我需要从该行获取数据。我发现这很像例子,但对我没有用:
var table = $('#table1').DataTable();
$('#myTable').on( 'click', 'tr', function () {
var id = table.row( this ).id();
alert( 'Clicked row id '+id );
} );
当我尝试这样做时,id 始终未定义。
var table = $('#table1').DataTable();
$('#example tbody').on('click', 'tr', function () {
var data = table.row(this).data();
alert('You clicked on ' + data[0] + '\'s row');
});
});
当我尝试这个时也是如此。我也看到了这个problem 对我没有帮助。
这是我的 HTML 表格:
<div class="container">
<table class="table table-hover" id="table1">
<thead>
<tr>
<th>Nome</th>
<th>Cgnome</th>
<th>Ani</th>
<th>Data</th>
<th>Paese</th>
....
</tr>
</thead>
</table>
</div>
这就是我在 javascript 中尝试过的:
var oTable1;
var id;
$('#table1').on('click', 'tbody tr', function () {
id = this.id; // is always `id = ""`
});
$(document).ready(function () {
LoadMissioniOptimizer();
});
function LoadMissioniOptimizer() {
$.ajax({
type: "GET",
url: "/My/GetAppSettingFromKey?key=MissioniOptimizer",
ASYNC: true,
dataType: "json",
success: function (data, textStatus, xhr) {
var apiUrl = data;
oTable1 =
$('#table1').DataTable({
ajax: '/api/staff',
rowId: 'staffId',
scrollY: '50vh',
scrollCollapse: true,
paging: false,
scrollX: true,
destroy: true,
serverSide: false,
processing: true,
searching: true,
ordering: true,
orderMulti: false,
colReorder: true,
paging: true,
columns: [
{ "data": "Nome", responsivePriority: 1, "searchable": true },
{ "data": "Cognome", responsivePriority: 2, "searchable": true },
{ "data": "Ani", responsivePriority: 3, "searchable": true },
{ "data": "Data", responsivePriority: 4, "searchable": true },
{ "data": "Paese", responsivePriority: 5, "searchable": true },
.......
],
columnDefs: [
{
render: $.fn.dataTable.render.text(),
targets: 0
},
{
render: $.fn.dataTable.render.text(),
targets: 1
},
{
render: $.fn.dataTable.render.text(),
targets: 2
},
{
render: $.fn.dataTable.render.text(),
targets: 3
},
{
render: $.fn.dataTable.render.text(),
targets: 4
},
]
});
$.ajaxSetup({ cache: false });
}
});
};
【问题讨论】:
-
您的 HTML 中没有
tbody,但您在点击功能中使用了'tbody tr'。 -
Ti consiglio non solo di ripassare i selettori ma anche di Considerare qualcosa di un po' più moderno, le table fatte con jquery sono da anni 90. Se poi lo fai per studio mi scuso。
-
即使没有 tbout 我总是得到 id = undefined
-
Cosa posso usare di piu moderno?
-
Ci sono diversi framework abbastanza conosciuti (per esempio il trio React-Vue-Angular),che hanno 来“伴奏”多样化的 librerie piuttosto fiche。 Ma mi rendo conto che per iniziare a studiare non sono il massimo。在 alternativa ci sarebbe Boostrap o Foundation... Ma di nuovo resumeto: se stai studiando le basi non è saggio sviare。 Ho detto di ripassare i selettori perché nello sn-p leggo "#example tbody",ma nell'HTML che hai aggiunto non mi sembra di vedere alcun id example。
标签: javascript jquery datatables