根据其他行中的内容筛选HTML表行

Filter HTML table rows based on content in other rows

本文关键字:筛选 HTML 表行 其他      更新时间:2023-09-26

我的HTML网站中有一个表,我正在有效地将其用作显示项目的列表。

每个项目都有:

  • 列[0]中的图像
  • 列[1]中的名称
  • 第[2]列中的说明

它比这稍微复杂一些,列[0]和[2]有一个rowspan="2",每个项在表中有第二行,它的两个类别显示在列[1]的名称下面。

这意味着它最终看起来像这样:https://jsfiddle.net/vapdp54z/2

我想在我的网站上的某个地方打勾,默认情况下,没有勾选,所有项目都显示出来。勾选复选框后,我希望隐藏所有没有复选框内容作为其类别的项目。

我在stackoverflow上发现了类似的问题,它们做了类似的事情,但它们对我不起作用,因为在我的情况下,我需要每隔一行检查一次,当没有找到匹配项时,它需要隐藏那一行和上面的那一行。

谢谢。

如果你的复选框看起来像这样:

<div>
  <input type="checkbox" name="categories" value="CATEGORY1"> Category One<br>
  <input type="checkbox" name="categories" value="CATEGORY2"> Category Two<br>
  <input type="checkbox" name="categories" value="CATEGORY3"> Category Three<br>
  <input type="checkbox" name="categories" value="CATEGORY4"> Category Four <br>
</div>

然后,您可以使用它们的值来隐藏任何包含匹配值的td的表行,也可以隐藏前一行,如下所示:

$(document).ready(function() {
    $('input[name=categories]').click(function() {
        // get the value of the clicked checkbox
        var cat = $(this).val();
        // select odd rows (the ones containing categories)
        $('tr:odd').each(function() {
            // get the td's in the row
            $('td', this).each(function() {
                // if the td html contains the category, 
                // hide its parent row and the previous row
                if ($(this).html().indexOf(cat) > -1)
                {
                    $(this).parent().css('display','none');
                    $(this).parent().prev().css('display','none');
                }
            });
        });
    });
});

当复选框未选中时,此解决方案不会处理隐藏行的撤消,但这将非常简单

以下是更新小提琴的链接:https://jsfiddle.net/vapdp54z/3/

我希望这能有所帮助!

编辑:我没有仔细阅读你的问题

如果您想隐藏不包含该类别的所有行,只需在IndexOf()检查

中将>更改为==