jQuery正则表格搜索不在所有列中搜索,只搜索第一列

时间:2014-01-23 19:04:20

标签: jquery regex search html-table

我终于让它工作了,我可以按名称搜索过滤。但是,我不能通过在任何列中搜索值来过滤它。例如,我希望能够输入'gmail'并仅显示那行中任何表格单元格中包含gmail的记录。即使我向class="name"添加td,它们也不会包含在搜索中。

HTML:

<input type="search" id="search" placeholder="Search table by name">

    <table caption="Data type 1" sortable id="name_table"><col width="20%"><col width="20%"><col width="15%"><col width="20%"><col width="25%">
        <thead>
            <tr>
                <th>Name</th><th>Address</th><th>Job No.</th><th class="no-sort">Phone</th><th>Email</th>
            </tr>
        </thead>
        <tfoot>
            <tr>
                <td colspan="5">End of records</td>
            </tr>
        </tfoot>
        <tbody>
            <tr>
                <td class="name">John Smith</td><td>123 Fake Street</td><td>Job 117</td><td>0405788996</td><td>john@company.co</td>
            </tr>
            <tr>
                <td class="name">Jane Smyth</td><td>1234 False Road</td><td>Job 118</td><td>0405788555</td><td>jane@hercompany.co</td>
            </tr>
            <tr>
                <td class="name">Alexey Fadeev</td><td>12 Dubio Lane</td><td>Job 119</td><td>0405788966</td><td>af@anothercompany.co</td>
            </tr>

        </tbody>
    </table>

使用Javascript:

<script>
    // Table Search
    $('#search').keyup(function() {
      var regex = new RegExp($('#search').val(), "i");
      var rows = $('table tbody tr');
      rows.each(function (index) {
        name = $(this).children(".name").html()
        if (name.search(regex) != -1) {
          $(this).show();
        } else {
          $(this).hide();
        }
      });
    });
</script>

我希望能够在我希望包含在搜索中的<tbody>中的每个列或单元格中添加一个类。有什么提示吗?

2 个答案:

答案 0 :(得分:1)

您没有在tr使用中包含所有文本

$(this).html(); or $(this).text();

而不是

name = $(this).children(".name").html();

答案 1 :(得分:0)

使用.html()方法时,它返回堆栈中第一个元素的HTML。我建议你改变这一行:

name = $(this).children(".name").html();

到此:

name = $(this).text();