【问题标题】:Jquery to hide table rows depending on multiple values from different columnsJquery根据来自不同列的多个值隐藏表行
【发布时间】:2015-11-09 01:35:48
【问题描述】:

我想在检查多列中接受的值后隐藏表格行。

表格是:

<table id="my-table>
<tr><td class="name">John</td><td class="lastname">Doe</td></tr>
<tr><td class="name">Ann</td><td class="lastname">Doe</td></tr>
<tr><td class="name">John</td><td class="lastname">Smith</td></tr>
</table>

根据我目前的研究(以及这个post),隐藏除 John Doe 之外的所有内容需要以下 Jquery 短语:

$("#my-table td.name:not(:contains('John')):td.lastname:not(:contains('Doe'))").parent().hide();

但是 Jquery 不喜欢这样说Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: td

这样做的正确方法是什么?

出于同样的原因,我想了解如何进行更复杂的查询,例如: Hide all rows with 'first name' containing 'a' OR 'b' AND 'last name' containing 'x' OR 'y'.

【问题讨论】:

  • 如何将本节中的冒号改为空格:td.lastname
  • 是的,我也试过了。在这种情况下,我不会收到错误消息,但也看不到对表的任何影响。所以这是一个不确定的测试。

标签: javascript jquery


【解决方案1】:

迭代每个 tr,然后检查每个 firstlast td

$( "tr" ).each( function( index, val ){
    if($(this).find("td:first-child").text() == 'John' && $(this).find("td:last-child").text() == 'Doe') {
        $(this).hide();
    }
});

Fiddle

更新:隐藏除 John Doe 以外的所有人

$( "tr" ).each( function( index, val ){
    if($(this).find("td:first-child").text() != 'John'  || $(this).find("td:last-child").text() != 'Doe') {
        $(this).hide();
    }
});

Fiddle

【讨论】:

  • 迭代是我最初认为应该完成的方式,但没有遇到.each() 函数。我喜欢 :) 你知道实用 Jquery 的一个很好的参考吗? C3School 几乎没有浮出水面。
  • PS:如何中断或继续这个 Jquery 迭代?例如,我想跳过第 0 行(标题行)。
  • @Benjamin 关于跳过标题行,如何将标题放入thead,然后将其他标题放入tbody 之类的this。然后在你的选择器$("tbody tr") 上,所以它只在tbody 中选择tr
  • @Benjamin 关于.text(),这真的取决于td 标签里面的内容。如果它只是名称,那么是的,这意味着不需要执行额外的代码来获取 content 属性的值,但是,请确保在使用 text() 时进行修剪。
  • @Benjamin 关于你的第一个问题,对不起,除了在 Stackoverflow 上询问/阅读帖子以及谷歌搜索之外,我没有特定的网站可供参考。
【解决方案2】:

因为:td 不是有效的伪选择器。您可以使用选择器#my-table td.name:not(:contains('John')),#my-table td.lastname:not(:contains('Doe'))。对于 multiple selector,您可以使用 ,

$("#my-table td.name:not(:contains('John')),#my-table td.lastname:not(:contains('Doe'))").parent().hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="my-table">
  <tr>
    <td class="name">John</td>
    <td class="lastname ">Doe</td>
  </tr>
  <tr>
    <td class="name ">Ann</td>
    <td class="lastname ">Doe</td>
  </tr>
  <tr>
    <td class="name ">John</td>
    <td class="lastname ">Smith</td>
  </tr>
</table>

【讨论】:

  • 从您链接到的参考资料中,我理解逗号分隔符的意思是 OR(不是 AND),但在您的示例中它用作 AND。我对如何问 AND 或 OR 感到困惑。你能澄清一下吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
  • 1970-01-01
相关资源
最近更新 更多