如果表中包含“NA”值的行,请将其删除

时间:2017-06-22 04:27:56

标签: javascript html

我有像这样的HTML代码。

<h4 id="dd">Resource usage</h4>
        <table border="1" class="dataframe table table-striped table-bordered table-hover">
  <thead>
    <tr style="text-align: right;">
      <th>peak_value</th>
      <th>resource_name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>NA</td>
      <td>NA</td>
    </tr>
    <tr>
      <td>NA</td>
      <td>NA</td>
    </tr>
  </tbody>
</table>

我从数据库中获取表。因此,数据是动态创建的。 现在我不想显示表,如果它的整行只有“NA”值(即),使用javascript值NA。 请帮帮我

2 个答案:

答案 0 :(得分:1)

您可以迭代td元素并查看是否有任何元素具有非NA值,如果不隐藏表格

var table = document.querySelector('#dd + table');
var toShow = Array.from(table.querySelectorAll('td')).some(td => td.innerHTML.trim() != 'NA');;
if (!toShow) {
  table.style.display = 'none';
}
<h4 id="dd">Resource usage</h4>
<table border="1" class="dataframe table table-striped table-bordered table-hover">
  <thead>
    <tr style="text-align: right;">
      <th>peak_value</th>
      <th>resource_name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>NA</td>
      <td>NA</td>
    </tr>
    <tr>
      <td>NA</td>
      <td>NA</td>
    </tr>
  </tbody>
</table>

演示:Fiddle

如果你想处理行

var table = document.querySelector('#dd + table');

var tableHasNonNAValue = false;
Array.from(table.querySelectorAll('tbody tr')).forEach(tr => {
  var hasNonNAValue = Array.from(tr.querySelectorAll('td')).some(td => td.innerHTML.trim() != 'NA');
  tableHasNonNAValue = tableHasNonNAValue || hasNonNAValue;
  if (!hasNonNAValue) {
    tr.style.display = 'none';
  }
});
if (!tableHasNonNAValue) {
  table.style.display = 'none';
}
<h4 id="dd">Resource usage</h4>
<table border="1" class="dataframe table table-striped table-bordered table-hover">
  <thead>
    <tr style="text-align: right;">
      <th>peak_value</th>
      <th>resource_name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>NA1</td>
      <td>NA</td>
    </tr>
    <tr>
      <td>NA</td>
      <td>NA</td>
    </tr>
  </tbody>
</table>

演示:Fiddle

答案 1 :(得分:0)

  • 使用jQuery.filter过滤所有td元素,文字为"NA"
  • 使用相应td元素中的tr元素的长度检查已过滤集合的长度
  • 如果trtd个元素且长度相等,hide() tr元素。

$('tr').each(function() {
  var tdElems = $(this).find('td');
  var filtered = tdElems.filter(function() {
    return this.textContent.trim() === 'NA';
  });
  if (tdElems.length && (filtered.length === tdElems.length)) {
    $(this).hide();
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4 id="dd">Resource usage</h4>
<table border="1" class="dataframe table table-striped table-bordered table-hover">
  <thead>
    <tr style="text-align: right;">
      <th>peak_value</th>
      <th>resource_name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>NA</td>
      <td>NA</td>
    </tr>
    <tr>
      <td>NA</td>
      <td>NA</td>
    </tr>
  </tbody>
</table>