javascript - 默认选择一行并使用 jQuery DataTables 发送 XHR 请求
问题描述
我正在尝试选择我的表的第一行并根据所选行通过 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>
解决方案
似乎问题出在绑定点击事件处理程序后触发点击事件。
这是该问题的有效 CodeSandbox 再现:https ://codesandbox.io/s/datatables-select-row-by-default-and-send-request-fnpu7
DataTables 现在createdRow
在其配置中没有处理函数的情况下被实例化,并且我们在单击事件绑定后使用 jQuery 单击触发器:
var table = $("#projects_table").DataTable();
// ...
$("#projects_table tbody").on("click", "tr", function(e) {
// ...
});
$("#projects_table tbody tr:first-child").trigger("click");
推荐阅读
- html - 渲染 PDF 错误字体粗细。只有或正在显示,其他是块
- javascript - 使用打字稿功能的Angular 6路由
- c - 当我从另一个链表中删除节点时,为什么我的链表值从另一个链表中被删除?
- java - 我将如何在我的代码中使用抽象类或接口来减少重复?
- jquery - Ajax 提交表单与 jquery 未验证
- reactjs - 如何在反应组件中找出道具是否是节点?
- python - 需要了解如何将数据分解为同一图表上的 2 条单独的线
- android - 在 Unity 奖励视频广告后打开 AppCompatDialogFragment 时出现错误/崩溃
- java - 如何修复新版本的 java 与 windows 10 和 libgdx 一起使用?
- lambda - 我们如何为 java8 函数、谓词、双函数做 junit