我在SO上看过很多线程,显示如何在enter上实现搜索(默认行为是在每次按键后搜索)但由于某种原因,当我对DataTables进行服务器端处理时,代码被忽略,默认行为又回来了。任何人都知道如何在用户按下回车后开始搜索?
这就是我现在所获得的并且搜索部分代码被忽略了(同时searchDelay没有效果 - 这来自DataTables文档)
var adminRoles;
$(document).ready(function () {
adminRoles = $('#adminRoles').dataTable({
info: true,
order: [[0, 'asc']],
processing: true,
serverSide: true,
searchDelay: 500, //does't work
ajax: {
url: "@Url.Action("GetRoles","Admin")",
type: "POST"
},
columnDefs: [
{ data: "Name", targets: 0 },
{ data: "KeyName", targets: 1 },
{
data: "Id",
className: "text-center editDetail clickable",
render: function (data, type, row) {
return '<button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-pencil text-primary" /></button>';
},
sortable: false,
searchable: false,
targets: 2
}
],
language: {
url: '@Url.Content(@Resource.js_DataTables_Language)'
}
}).api();
$('#adminRoles_filter input').unbind().bind('keypress', function (e) {
if (e.which == 13) {
alert('You pressed enter!'); //doesn't get hit
//adminRoles.search(this.value).draw();
}
return;
});
});
答案 0 :(得分:6)
使用initComplete
选项定义在初始化表时将调用的函数,并使用以下代码搜索 Enter 键。
adminRoles = $('#adminRoles').dataTable({
initComplete: function(){
var api = this.api();
$('#adminRoles_filter input')
.off('.DT')
.on('keyup.DT', function (e) {
if (e.keyCode == 13) {
api.search(this.value).draw();
}
});
},
// ... skipped ...
});
答案 1 :(得分:0)
我明白了。问题出在语言网址上。呈现DataTables时,它等待语言文件完全读取,然后才能显示。绑定和取消绑定操作无法完成,因为输入元素不存在。所以,为了反驳我已经在fnInitComplete上添加了它,就像有人在DataTables论坛上建议的那样。您还需要fnFilterOnReturn.js
p
};
代码:
jQuery.fn.dataTableExt.oApi.fnFilterOnReturn = function (oSettings) {
var _that = this;
this.each(function (i) {
$.fn.dataTableExt.iApiIndex = i;
var $this = this;
var anControl = $('input', _that.fnSettings().aanFeatures.f);
anControl
.unbind('keyup search input')
.bind('keypress', function (e) {
if (e.which == 13) {
$.fn.dataTableExt.iApiIndex = i;
_that.fnFilter(anControl.val());
}
});
return this;
});
return this;