【问题标题】:jQuery search through table rows, hidden and visiblejQuery通过表格行搜索,隐藏和可见
【发布时间】:2025-12-08 21:55:02
【问题描述】:

我有一个表格,我可以在其中显示消息历史记录。默认情况下,该表仅显示两个人之间的最后一条消息。但是所有的消息都在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 状态

jsfiddle:

http://jsfiddle.net/2T5yJ/

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

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

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

    删除

     if (!index) return;
    

    搜索过滤器可以正常工作

    更新你可以检查value="" 并编写逻辑以恢复原始行的显示

    请检查更新的小提琴

    FIDDLE

    【讨论】:

    • 搜索所有trs,但不会重新隐藏Aquincum cpp code