简体   繁体   English

在 Html 表中搜索(在 Td 特定子标签中)并隐藏行

[英]Search in Html-table (in Td Specific Child Tag) and Hide Row

I want the table to be searched only in the H3 tag, not TD tag.我希望只在 H3 标签中搜索表格,而不是 TD 标签。 And if a result is found, its TR should be hidden -h3 is a Child tag under TD.并且如果找到一个结果,它的TR应该被隐藏-h3是TD下的一个Child标签。

for Example:例如:

<tr>
  <td>
    <h3>Hier</h3>
    <div></div>
  </td>
</tr>

<script>
$(document).ready(function(){
        $("#myInput").on("keyup", function() {
            const value = $(this).val().toLowerCase();
            $("#myTable tr").filter(function() {
                $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
            });
            console.log(value);
        });
    });
</script>

Thank you For Help谢谢你的帮助

The main issue in your code is because you're searching through the text of the tr as a whole.您的代码中的主要问题是因为您正在搜索整个tr的文本。 You need to call find('h3') and then compare to the text in that element.您需要调用find('h3')然后与该元素中的文本进行比较。

Also note that filter() is intended to do just that;另请注意, filter()旨在做到这一点; filter a collection of elements and return a subset of them.过滤一组元素并返回其中的一个子集。 You shouldn't call toggle() within it.您不应该在其中调用toggle() Instead call hide() , filter to find matches, then show() them.而是调用hide() ,过滤以查找匹配项,然后show()它们。

 jQuery($ => { $("#search").on('input', e => { const value = $(e.target).val().toLowerCase().trim(); $("table tr").hide() .filter((i, tr) => $(tr).find('h3').text().toLowerCase().indexOf(value) > -1).show(); }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <input type="text" name="search" id="search" /> <table> <tr> <td> <h3>Foo</h3> <div></div> </td> </tr> <tr> <td> <h3>Foo bar</h3> <div></div> </td> </tr> <tr> <td> <h3>Hier</h3> <div></div> </td> </tr> </table>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM