【问题标题】:Hide table td if contain exact match如果包含完全匹配,则隐藏表 td
【发布时间】:2013-12-06 13:33:39
【问题描述】:

如果我的所有表 td 只包含符号“%”,我需要隐藏它们。

我有两种结果:

<td>%</td>
<td>1%</td>

我想隐藏所有只有 % 的 td。 % 前面有 1% 或 2% 或任何其他数字的那些必须保持可见。

我做了一个 js,但它隐藏了所有的 td(我完全理解为什么:因为我使用了 :contains 并且如果 td 包含 % 那么它将被隐藏):

if (jQuery('#results table tbody tr td:contains("%")').length > 0) {
    jQuery("#results table tbody tr td").hide();
}

我需要知道如何做到这一点。 谢谢

【问题讨论】:

  • 你的 jQuery 错了,你对它为什么错的想法也是错的。您已经编写了两个完全独立的 jQuery 选择器。 if 中的那个与if 条件中的那个无关。您两次都选择了不同的元素。在if 中,您需要引用由first jQuery(...) 找到的结果,将它们存储在变量中或使用each/filter/etc 迭代它们。

标签: javascript jquery html coding-style


【解决方案1】:

我会使用.filter:

$("#results table tbody tr td").filter(function() {
    return $(this).text() === "%";
}).parent().hide();

这里有一个jsFiddle 来演示。

【讨论】:

  • 我的立场是正确的,它确实返回了一个 jQuery 对象。这将是更好的解决方案。
  • @Stan 只需在.hide() 之前打一个.parent() 电话
  • @RGraham 非常感谢。现在完美了。
【解决方案2】:

试试eachlike

$('#results table tbody tr td').each(function(){
     if($(this).text() == "%") {
         $(this).hide();
     }
});

【讨论】:

    【解决方案3】:

    试试这个

    $('#results table tbody tr td').each(function(){
         if($(this).text().indexOf('%')!=-1)
         {
             $(this).hide();
         }
    });
    

    【讨论】:

    • 这将隐藏每个包含%&lt;td&gt; 在其中的任何位置。包括他不想隐藏的&lt;td&gt;%1&lt;/td&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 2012-07-11
    • 2012-02-17
    • 2020-10-21
    相关资源
    最近更新 更多