在初始化数据表后,我必须在一个函数中更改列的 bSearchable
属性。我需要先启用然后禁用它。
我找到了一个可见性示例:
$(document).ready(function() {
var table = $('#example').DataTable( {
"scrollY": "200px",
"paging": false
} );
$('a.toggle-vis').on( 'click', function (e) {
e.preventDefault();
// Get the column API object
var column = table.column( $(this).attr('data-column') );
// Toggle the visibility
column.visible( ! column.visible() );
} );
} );
我的情况也可以使用类似的东西吗?类似于column.seachable
?
最佳答案
这是一个老问题,但我花了几个小时来研究答案......主要是因为我缺乏 JS 技能。
用例是我有一个表,其中的 ID 列是 GUID
。该Id很少使用,占用大量空间,所以默认是隐藏的,不可搜索。但对于可能有权访问日志或数据库的内部用户,我们还需要能够搜索 ID 列。
我为这些用户添加了一个复选框,它应该会更改 ID 列的可见性和可搜索属性。
我的解决方案基于another question regarding searching on columns 。但在这个问题中,搜索仅针对单个列,而不是针对所有可搜索列(普通 DataTable.search()
API)。遗憾的是,要更改 searchable
属性,似乎没有公共(public) API。如果更改 searchable
属性,则必须随后使表中的数据无效,否则列数据仍将存在/不存在于表 aoFilterData
中。这会强制表从数据源(在本例中为 DOM)重新加载数据。
我在正确的位置注册事件处理程序时遇到了很多问题。过滤器字段在表的第一个 draw
事件中不存在,因此我必须在表完全初始化后触发的 init
事件中注册处理程序。
var userTable;
var idSearchCbx;
var searchField;
$(document).ready(function () {
userTable = document.getElementById("table-users");
if (userTable) {
userTable = $("#table-users").DataTable(
{
"columnDefs": [
{
//First column invisible and not searchable by default
"targets": [0], //first column = ID
"visible": false,
"searchable": false
}],
//Other initialization options
); //Table creation
userTable.on("init",
function () {
$("input[type='search']").on("change cut input keypress keyup paste search recheck",
function () {
var searchValue = $(this).val();
userTable.search(searchValue).draw();
//width attribute is calculated and added to the table
//it loses 2 pixels everytime the checkbox is checked/
//unchecked somehow - so delete it
document.getElementById("table-users").removeAttribute("style");
});
idSearchCbx = $("#cbx-search-id");
idSearchCbx.on("change",
function () {
if (this.checked === true) {
//this makes the first column searchable, not official API
userTable.context[0].aoColumns[0].bSearchable = true;
//make it visible as well, official API
userTable.columns(0).visible(true);
//invalidates cached table data so that the column values are
//added to the filterdata
userTable.rows().invalidate().draw();
} else {
userTable.context[0].aoColumns[0].bSearchable = false;
userTable.columns(0).visible(false);
userTable.rows().invalidate().draw();
}
//trigger the normal search again so that the
//filter is / is not applied to the first column
$("input[type='search']").trigger("recheck");
});
}); //DT on init
} //table present
});//document ready
我假设上下文与settings()
相关。 ,因此请记住,上下文中的名称可能会发生变化,即使在次要版本中,这也很可能不是版本稳定的。但我没有找到任何其他方法。希望它对某人有帮助。
关于javascript - 动态更改可搜索数据表列属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46782605/