单元格为空时隐藏表格行

时间:2015-01-21 14:11:03

标签: css

我遇到的问题似乎无法找到答案,但我无法想象这是不可能的。

我有一个包含两列的表:左列包含标签,右侧包含一个值。但是,该值可以为空。标签是固定文本。

如果行的右侧单元格(值)为空,我想隐藏整行。

例如:

<table>
 <tr>
  <td class="label">number of users:</td>
   <td class="value">8</td>
 </tr>
 <tr>
  <td class="label">total number of people:</td>
  <td class="value"></td>
 </tr>
</table>

由于最后一行不包含值,我希望隐藏整行。

我可以使用td:empty隐藏单元格,但这还不够。我尝试通过将行的高度设置为0px来解决这个问题,并在显示“value”单元格时将其展开,但由于标签单元格已经扩展了行,我无法使其工作。

任何人都知道如何使用HTML / CSS来解决这个问题?

2 个答案:

答案 0 :(得分:4)

css中没有父选择器,因此您无法使用css执行此操作。

您可以使用jQuery:

$('td').each(function(){
  if($(this).is(:empty)){
     $(this).closest('tr').hide();
  }
});

或者是缩写形式,

$('tr:has("td:empty")').hide();

请参阅文档::empty:hasclosesteach

答案 1 :(得分:2)

虽然JavaScript是解决这个问题的必要条件,但jQuery绝不是必需的。使用DOM,可以通过以下方式实现此目的:

function hideParentsOf(cssSelector) {
    var elems = document.querySelectorAll(cssSelector);
    if (elems.length) {
        Array.prototype.forEach.call(elems, function (el) {
            el.parentNode.style.display = 'none';
        });
    }
}

hideParentsOf('td:empty');

&#13;
&#13;
function hideParentsOf(cssSelector) {
  // cssSelector: String,
  //              a string representing a CSS selector,
  //              such as 'td:empty' in this case.

  // retrieving a NodeList of elements matching the supplied selector:
  var elems = document.querySelectorAll(cssSelector);

  // if any elements were found:
  if (elems.length) {
    // iterating over the array-like NodeList with Array.forEach():
    Array.prototype.forEach.call(elems, function(el) {
      // el is the current array-element (or NodeList-element in
      // this instance).
      // here we find the parentNode, and set its 'display' to 'none':
      el.parentNode.style.display = 'none';
    });
  }
}

hideParentsOf('td:empty');
&#13;
<table>
  <tr>
    <td class="label">number of users:</td>
    <td class="value">8</td>
  </tr>
  <tr>
    <td class="label">total number of people:</td>
    <td class="value"></td>
  </tr>
</table>
&#13;
&#13;
&#13;

参考文献: