我正在使用DataTables jQuery 插件。
我想搜索表格中的术语是否显示在两个特定列中的至少一列中。
下面的当前代码仅查找单词“word”
同时出现在两列中的行。我需要查找该单词位于任一列中的行。
$table.DataTable().columns([0,1]).search("word");
我考虑过使用全局搜索并将其他列的可搜索选项设置为 false,但我找不到在运行时更改此选项的方法。
最佳答案
搜索所有列
搜索表时可以使用正则表达式。
例如,下面的代码显示包含单词 Angelica
的搜索结果或London
在所有列中。
var table = $('#example').DataTable();
table
.search('Angelica|London', true, false)
.draw();
参见this jsFiddle用于代码和演示。
搜索特定列
要搜索特定列,您可能需要使用 custom search功能。
下面的代码显示包含单词 Angelica
的搜索结果或Tokyo
在带有索引的表数据值中 0
, 1
,和2
.
var table = $('#example').DataTable();
var terms = ['Angelica', 'Tokyo'];
// Convert terms to lower case
$.each(terms, function(index, value){
terms[index] = value.toLowerCase();
});
// Enable custom search
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var isFound = false;
$.each(data, function (index, value){
// Evaluate only first three data values
if(index === 0 || index === 1 || index === 2){
// Convert data to lower case
value = value.toLowerCase();
$.each(terms, function(termIndex, termValue){
// If data contains the term
if (value.indexOf(termValue) !== -1) {
isFound = true;
}
return !isFound;
});
}
return !isFound;
});
return isFound;
}
);
// Perform search
table.draw();
// Disable custom search
$.fn.dataTable.ext.search.pop();
参见this jsFiddle用于代码和演示。
关于javascript - 数据表或搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36430006/