代码之家  ›  专栏  ›  技术社区  ›  matt

jQuery扫描表th的*并给父级一个颜色

  •  2
  • matt  · 技术社区  · 14 年前

    对于我来说,jQuery的任务相当复杂。

    我要扫描整个表中的th元素。如果th元素中有星号(*),我想突出显示父元素,即tr元素。

    我知道我解释的时候听起来很复杂:)

    因此,假设我有一个动态html表,我想在其中启用一个特性来显示某些行。因此,我只想把一些符号(在我的例子中是星号*)放在表格单元格内的一些文本中。如果jQuery在th中检测到星号,它应该自动给其父()一个类名!

    一个开始可能是每个函数的一个开始:

    $(function() {
        $("table tr th").each(function() {
            $(this).parent().addClass("special");            
        });
    });
    

    2 回复  |  直到 8 年前
        1
  •  3
  •   Hari Pachuveetil    14 年前

    这可能有助于:

    $(function() {
        $("table tr th").each(function() {
            if ($(this).text().indexOf('*') > -1)            
                $(this).closest('tr').addClass("special");            
        });
    });
    

    编辑:你可能想要 th 自己有一个 special 演示中的类 here

        2
  •  1
  •   Gert Grenander Keiron Lowe    14 年前

    $("table tr th:contains('*')").parent().addClass("special");
    

    Example at jsfiddle.

    根据OP的评论编辑:

    为了删除星号,您需要遍历找到的元素:

    $("table tr th:contains('*')").each(function(){
      var $This=$(this);
    
      $This.parent().addClass("special"); /* Add the "special" class */
      $This.text($This.text().replace("*","")); /* Remove the asterisk */
    });
    

    Example with asterisk removal.