首页 > 解决方案 > 如何通过任何匹配的代码/名称而不是每个可用字段来过滤表

问题描述

我正在尝试执行以下操作:我有一个填充了数据库数据的表。除此之外,我还有一个输入,您可以在其中写一些东西,还有一个可以过滤的按钮,只显示具有该字符串的行。这正在工作!

问题是,输入应该只允许您过滤foo.name/foo.code(我的实体的两个属性)。

我正在添加我拥有的代码,以防有人可以指导我,我已经尝试了几件事,但这是我第一次使用 JQuery,而我有严格的故事交付时间。感谢大家!

<tbody>
    <c:forEach var="foo" items="${foo}">    
        <tr id = "fooInformation" class="mtrow">
            <th id="fooName" scope="row">${foo.name}</th>
            <td id="fooCode" class="left-align-text">${foo.code}</td>       
            <td class="left-align-text">${foo.country}</td>
            <td class="left-align-text">${foo.region}</td>
            <td class="left-align-text">${foo.subregion}</td>  
        </tr>
    </c:forEach>
</tbody>
    
$("#search").click(function () { -> button id
    var value = $("#fooRegionSearch").val(); -> value of the input
    var rows = $("#fooRegionTable").find("tr"); -> table id
    rows.hide();
    rows.filter(":contains('" + value + "')").show();
});

标签: javascriptjquery

解决方案


首先,您的 HTML 无效 - HTML 中不能有具有重复 ID 的元素。使用类而不是 ID。

然后,您需要确定哪些 TR 通过了测试。.filter可以接受一个回调,所以给它一个函数,给定一个 TR,选择它的fooNamefooCode包含value使用:containsjQuery 选择器的子元素:

$("#search").click(function() {
  var value = $("#fooRegionSearch").val();
  var rows = $("#fooRegionTable").find("tr");
  rows.hide();
  rows.filter(
    (_, row) => $(row).find('.fooName, .fooCode').filter(`:contains('${value}')`).length
  ).show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="fooRegionTable">
  <tr id="fooInformation" class="mtrow">
    <th class="fooName" scope="row">name1</th>
    <td class="fooCode" class="left-align-text">code1</td>
    <td class="left-align-text">${foo.country}</td>
    <td class="left-align-text">${foo.region}</td>
    <td class="left-align-text">${foo.subregion}</td>
  </tr>
  <tr id="fooInformation" class="mtrow">
    <th class="fooName" scope="row">name2</th>
    <td class="fooCode" class="left-align-text">code2</td>
    <td class="left-align-text">${foo.country}</td>
    <td class="left-align-text">${foo.region}</td>
    <td class="left-align-text">${foo.subregion}</td>
  </tr>
</table>
<button id="search">click</button><input id="fooRegionSearch" />


推荐阅读