我有一个使用 php 动态填充的表格,我想为其添加搜索功能。 在堆栈溢出上搜索类似的问题后,我发现了一个我尝试过的JS片段。
var $rows = $('#existing tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
JSFIDDLE 链接: http://jsfiddle.net/kvkBw/3/
问题是当我输入任何搜索词时,表格本身会被隐藏(不可见)任何帮助将不胜感激,谢谢!
请注意,php 代码被删除是因为 jsfiddle 不支持 php,也是为了提高可读性
首先,你的函数搜索是错误的,什么是!~
,为什么你试图隐藏你找到的所有出现?
试试这个:
var $rows = $('#existing tbody tr:not(:first)'); // this is the reason for table hidding like @drizzie says
$('#search').keyup(function () {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.hide().filter(function () {
var text = $(this).text().replace(/s+/g, ' ').toLowerCase();
return text.indexOf(val) != -1 ;
}).show();
});
但最好看看演示
您正在隐藏第一行和第二行。 将行选择器更改为
var $rows = $('#existing tbody tr:not(:first)');
这将消除标题行和筛选器行。
删除最后的 .hide(),这是导致您的问题的原因。
同时删除返回值开头的 !
$rows.show().filter(function () {
var text = $(this).text().replace(/s+/g, ' ').toLowerCase();
return text.indexOf(val);
});