使用输入文本框搜索并过滤html表数据

时间:2013-10-29 19:57:57

标签: javascript php jquery html

我有一个使用php动态填充的表。我想为它添加搜索功能。在stackoverflow上搜索类似问题后,我找到了一个我试过的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,也提高了可读性

3 个答案:

答案 0 :(得分:3)

首先,你的功能搜索是错误的,什么是!~,以及为什么你试图隐藏你发现的所有事件?

试试这个:

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();
});

但最好看看 DEMO

答案 1 :(得分:0)

删除导致问题的最后一个.hide()。

同时删除!在返回值的开头。

   $rows.show().filter(function () {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return text.indexOf(val);
    });

答案 2 :(得分:0)

您正在隐藏第一行和第二行。将行选择器更改为

var $rows = $('#existing tbody tr:not(:first)');

这会删除标题行和过滤器行。

相关问题