繁体   English   中英

当TD包含特定类别时隐藏TR

[英]Hiding TR when TD contains specific class

我的PHP页面上有以下Javascript代码,我将表名和一个变量传递给该函数。 代码的“ ALL”部分工作正常,可在页面中进行解析,并将所有CSS样式的显示描述符从“ none”翻转为“ n”或“ back”。

我遇到问题的地方是“红色”部分。 应该隐藏所有包含类“ RedCell”的TD的TR,但是我似乎无法使这部分按预期工作。 请帮忙。

JAVASCRIPT

function expandCollapseTable(tableObj, which)
{
 if (which == 'ALL')
    {
      var rowCount = tableObj.rows.length;
      for(var row=0; row<rowCount; row++)
      {
        rowObj = tableObj.rows[row];
        rowObj.style.display = (rowObj.style.display=='none') ? '' : 'none';
      }

      return;
    }

  if (which == 'RED')
    {
      $('td.RedCell').find('td.RedCell').closest('tr').style.display =  'none';
      return;
    } 

  else
    {
      return;
    }
}

CSS

.ResultTable td.RedCell{
    background-color:#FF4747;
}

HTML按钮和示例表

<input type="button" value="Show/hide ALL" onclick="expandCollapseTable(TheTable, 'ALL')" />

<input type="button" value="Hide Red" onclick="expandCollapseTable(TheTable, 'RED')" />

<table id="TheTable" class="ResultTable" style="padding: 0px; background: #FFFFFF;" align="center">
<tr><td class="RedCell">2014-07-17 10:04</td><td>1998847</td><td>137717</td></tr>
<tr><td>2014-08-06 10:44</td><td>2009211</td><td>106345</td>
<tr><td class="RedCell">2014-07-31 16:47</td><td>2006727</td><td>138438</td>

因此,第一行和第三行将被隐藏,第二行保持可见

CodePen版本的代码http://codepen.io/anon/pen/DrKLm

它应该是:

$('td.RedCell', tableObj).closest('tr').hide();

要将呼叫.find()一直在寻找另一个td.RedCell的第一个

另外,您不能将.style属性与jQuery对象一起使用,即用于DOM元素。 要使用jQuery隐藏某些内容,请使用.hide().css("display", "none")

并且您需要将搜索限制在给定的tableObj

顺便说一句,为什么不将jQuery用于ALL选项? 整个循环可以替换为:

$("tr", tableObj).toggle();

.find说的两个问题是查找td.RedCells的后代。 这些都没有...

然后,使用.css设置样式。

所以这:

$('td.RedCell').closest('tr').css('display', 'none');

而不是从子级到父级,使用jQuery :has选择器基于后代过滤元素。

$(tableObj).find('tr:has(td.RedCell)').hide();

此外,您可能只想在所有单元格都未隐藏的情况下才将其隐藏。 如果隐藏了任何内容,则需要显示这些内容,并使其余部分可见。 这是一个例子...

var rows = $(tableObj).find('tr:gt(0)'); // Skips the first row
if(rows.is(':hidden')) {
    // Contains elements which are hidden
    rows.show();
} else {
    rows.hide();
}

结果将是:

function expandCollapseTable(tableObj, which) {
    var rows = $(tableObj).find('tr:gt(0)');
    if(which == 'RED') {
        // First snippet
        rows.has('td.RedCell').hide();
    } else if(which == 'ALL') {
        // Second snippet
        if(rows.is(':hidden')) {
            rows.show();
        } else {
            rows.hide();
        }
    }
}

http://codepen.io/anon/pen/xlmcK

额外的编程功能:

第二个片段可以简化为rows[rows.is(':hidden')?'show':'hide']();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM