我正在尝试选择表格的第一行并根据所选行通过ajax发送请求。到目前为止,我只能选择第一行,但仍然无法发送请求。
逻辑
代码
var row = $(this).closest('tr');
var table = $("#projects_table").DataTable({
'createdRow': function(row, data, dataIndex) {
if (dataIndex == 0) {
$(row).addClass('selected'); // selected row (first one)
};
setTimeout( function () {
table.draw();
}, 100 );
}
});
$('#projects_table tbody').on( 'click', 'tr', function (e) {
$('.addVisit').hide();
e.preventDefault();
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
var scheduleID = '';
var projectID = '';
$('.projectName').empty();
$('#projectName').empty();
} else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
$('.projectName').empty();
$('#projectName').empty();
var projectID = $(this).data('id'); //this should get data-id of selected row above
$.ajax({
type:'GET',
url:'{{url('dashboard/getProjectVisits')}}/'+projectID, //this should be excuted
success:function(data){
// retunting my data in second table and this process repeats
// for all my tables in this view.
// (to clear the code i removed this part)
}
});
}
});
有什么想法吗?
更新
这是我的表格 HTML 代码
<!-- projects table -->
<div class="col-md-6">
<div class="panel">
<div class="panel-heading">
<h6 class="panel-title">Projects</h6>
</div>
<div class="panel-body">
<table id="projects_table" class="table table-striped table-bordered">
<thead>
<tr>
<th>Project</th>
</tr>
</thead>
<tbody id="projects_table2">
@foreach($projects as $project)
<tr data-id="{{$project->id}}">
<td>{{$project->name}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
<!-- visits table -->
<div class="col-md-6">
<div class="panel">
<div class="panel-heading">
<h6 class="panel-title"><span class="projectName"></span> Visits</h6>
</div>
<div class="panel-body">
<table id="schedule_table" class="table table-striped table-bordered">
<thead>
<tr>
<th>From Date</th>
<th>To Date</th>
<th>Location</th>
<th>Description</th>
<th>Status</th>
</tr>
</thead>
<tbody id="schedule_table2"></tbody>
</table>
</div>
</div>
</div>
最佳答案
问题似乎出在绑定(bind)点击事件处理程序后触发点击事件。
这是该问题的有效 CodeSandbox 再现:https://codesandbox.io/s/datatables-select-row-by-default-and-send-request-fnpu7
DataTables 现在实例化,其配置中没有 createdRow
处理函数,并且我们在单击事件绑定(bind)后使用 jQuery 单击触发器:
var table = $("#projects_table").DataTable();
// ...
$("#projects_table tbody").on("click", "tr", function(e) {
// ...
});
$("#projects_table tbody tr:first-child").trigger("click");
关于javascript - 默认选择一行并使用 jQuery DataTables 发送 XHR 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59463845/