【问题标题】:Test if children contain specific text with jQuery使用 jQuery 测试子项是否包含特定文本
【发布时间】:2012-08-03 04:08:40
【问题描述】:

我必须过滤一个 html 表。为此,我为所有 tr 元素创建了一个 each 回调,并测试其中一个 tr-children 是否包含某些特定模式。

$("#filter").keypress(function() {
    var filter = $(this).val();

    $("#table1 tr[data-config]").each(function(){

        var val = $(this).find(":contains('" + filter + "')");

        if(val.length > 0){
            $(this).css("display","table-row");
        }else{
            $(this).css("display","none");
        }
    });
});

它可以工作,但是是否有一个函数可以测试一个元素是否包含一些文本?

目前,我检索包含该模式的所有元素的列表,并计算它是否大于零。是否有一个 jQuery 函数来测试这种模式是否发生并返回一个布尔值?该表可以包含许多行,因此我希望尽可能少的开销。

【问题讨论】:

  • 嗨,NaN,如果您想发布答案,请联系我,我会删除我的(标记为社区 wiki)。否则,只需将此评论标记为已过时。谢谢!

标签: jquery html css filter


【解决方案1】:

答案很好,但是使用 :contains 有一种更简单的方法

一般来说,这样做:

$(".class:contains('texttofind')").css("display", "none");

根据上面的具体例子,这样做:

$("#table1 tr[data-config]:contains('" + filter + "')").css("display","table-row");

您可以在此处了解更多信息:https://api.jquery.com/contains-selector/

这避免了循环使用.each.find

【讨论】:

    【解决方案2】:

    当过滤器区分大小写时,这是使其不区分大小写的方法:

    .match("/pattern/i"); 
    

    Billy!

    【讨论】:

      【解决方案3】:
      ///// replace these lines...
      // var val = $(this).find(":contains('" + filter + "')");
      // if(val.length > 0){
      
      ///// with this line
      if($(this).text().match(filter)){
      

      这通过将整行内容转换为文本字符串,然后使用简单的字符串比较函数来检查过滤器是否包含在文本(以及行)中

      【讨论】:

        猜你喜欢
        • 2014-02-07
        • 1970-01-01
        • 2016-07-27
        • 2011-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-16
        • 1970-01-01
        相关资源
        最近更新 更多