根据其他行中的内容过滤HTML表行

时间:2015-11-28 05:02:11

标签: javascript jquery html html-table

我的HTML网站上有一个表格,我实际上将其用作显示项目的列表。

每个项目都有:

  • 第[0]栏中的图像
  • 列[1]
  • 中的名称
  • 第[2]栏
  • 中的描述

稍微复杂一点,虽然列[0]和[2]有一个rowspan="2",每个项目在表格中有第二行,其中两个类别显示在列[1]中的名称下方

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

我想在我的网站上的某个地方使用复选框,默认情况下,没有勾选所有项目。勾选复选框后,我希望隐藏所有项目,但没有将复选框内容作为其类别之一。

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

感谢。

1 个答案:

答案 0 :(得分:0)

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

<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/

我希望这有帮助!

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

如果要隐藏不要包含该类别的所有行,只需更改&gt;在IndexOf()检查中输入==

相关问题