问题描述
您好我正在使用,我想用一个确切的词来过滤我的数据。
Hi I'm using datatables and I would like to filter my data by an exact word.
我的表数据如下所示;
My table data looks like below;
+-----+----------+
| num | status |
+-----+----------+
| 1 | Active |
+-----+----------+
| 2 | Inactive |
+-----+----------+
| 3 | Active |
+-----+----------+
每当我搜索 Active
时,我也会看到所有非活动
。有没有办法过滤这个,以便状态列只显示确切的单词。
Whenever I search for Active
I also see all the Inactive
too. Is there any way to filter this so that either the status column only shows exact words.
我的JS在下面;
$(document).ready(function() {
var table = $('#items').DataTable( {
select: true,
responsive: true
} );
} );
我一直在阅读但是我无法理解它。也许我需要写一些正则表达式?
I've been reading through the API however I can't make much sense of it. Perhaps I need to write some regex?
有一个例子(我认为),但我需要根据我的需要对其进行修改。
There's an example (I think) here, however I need to modify it to my needs.
任何帮助或建议都将不胜感激。
Any help or advice would be appreciated.
推荐答案
如果认为你最好用。 取消绑定
默认处理程序并每次执行完全匹配过滤器。如果你有一个表
If think you are better off with a custom filter for this task. unbind
the default handlers and perform a exact match filter each time instead. If you have a table
var table = $('#example').DataTable()
然后以这种方式使用完全匹配的自定义过滤器
Then use a exact match custom filter this way
$('.dataTables_filter input').unbind().bind('keyup', function() {
var searchTerm = this.value.toLowerCase()
if (!searchTerm) {
table.draw()
return
}
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
for (var i=0;i<data.length;i++) {
if (data[i].toLowerCase() == searchTerm) return true
}
return false
})
table.draw();
$.fn.dataTable.ext.search.pop()
})
这是一个演示 - > 尝试搜索 tokyo
。
here is a demo -> http://jsfiddle.net/hmjnqjbs/1/ try search for tokyo
.
好的。我意识到问题不在于精确匹配过滤器中的精确单词,而是整个单词搜索。当我们搜索 vaio
时,我们希望看到 Vaio Q900
,但我们不希望看到 VaioQ900
因为 Vaio
这里不是一个完整的词。通过使用正则表达式字边界 \b
来解决此问题:
OK. I realize the question not is about "exact words" as in exact match filter, but more a whole word search. We want to see Vaio Q900
when we search on vaio
, but we do not want to see VaioQ900
because Vaio
here not is a whole word. This problem is simply solved by using a regex word boundary \b
:
$('.dataTables_filter input').unbind().bind('keyup', function() {
var searchTerm = this.value.toLowerCase(),
regex = '\\b' + searchTerm + '\\b';
table.rows().search(regex, true, false).draw();
})
来自下面评论的OP的小提琴 - >
OP's fiddle from the comment below updated -> http://jsfiddle.net/hmjnqjbs/3/
现在活动
, vaio
等按预期工作。
Now active
, vaio
and so on works as expected.
这篇关于数据表精确的单词搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!