jQuery搜索表行,隐藏和可见

时间:2014-03-26 08:51:43

标签: javascript jquery

我有一张表格,其中显示了消息历史记录。默认情况下,该表仅显示两个人之间的最后一条消息。但是所有邮件都在HTML代码中,只是它们设置为display:none;

我试图让搜索遍历可见和隐藏的tr行。

我现在有什么:

HTML:

            <table cellpadding="0" cellspacing="0" width="100%" class="tDefault mytasks" id="history">
                    <tr>
                        <td>Finish design</td>
                        <td align="center"><strong class="grey">0%</strong></td>
                    </tr>
                    <tr>
                        <td>Aquincum HTML code</td>
                        <td align="center"><strong class="green">89%</strong></td>
                    </tr>
                    <tr style="display:none;">
                        <td>Aquincum cpp code</td>
                        <td align="center"><strong class="green">99%</strong></td>
                    </tr>                            

                    <tr>
                        <td>Fix buggy css styles</td>
                        <td align="center"><strong class="red">16%</strong></td>
                    </tr>

            </table>

jQuery的:

$("#search").keyup(function() {
    var value = this.value.toLowerCase().trim();

    $("#history tr").each(function (index) {
        if (!index) return;
        $(this).find("td").each(function () {
            var id = $(this).text().toLowerCase().trim();
            var not_found = (id.indexOf(value) == -1);
            $(this).closest('tr').toggle(!not_found);
            return not_found;
        });
    });
});

我有两个问题:

  1. 出于某种原因,第一个tr始终可见,即使它与搜索不匹配。尝试搜索buggy css。您会看到第一个tr仍在那里。

  2. 当我搜索某些内容,然后清除搜索字段。默认情况下设置为tr的第二个display:none;是可见的。它必须以某种方式回到display:none

  3. 的jsfiddle:

    http://jsfiddle.net/2T5yJ/

1 个答案:

答案 0 :(得分:1)

对于第一行索引为零。所以它没有达到

        $(this).find("td").each(function () {

删除

 if (!index) return;

搜索过滤器可以正常工作

更新您可以检查是否value=""并编写逻辑以将行显示为原始

请检查更新的小提琴

FIDDLE