【问题标题】:Deleting null rows from HTML table with Javascript使用 Javascript 从 HTML 表中删除空行
【发布时间】:2019-05-27 10:52:44
【问题描述】:

我有一个从数据库中提取的 HTML 表。一些行与文本 null 一起出现,我想遍历此表并删除或隐藏其中包含文本 null 的任何行。

第一列将是循环遍历并找到“空”文本并删除该行的列,但我不知道该怎么做。

<table class="table table-striped" id="ex-table">
  <thead class="thead-inverse">
    <col width="120">
    <col width="120">
    <col width="120">
    <tr>
      <th bgcolor="#feaf3f">Item</th>
      <th bgcolor="#feaf3f">Price</th>
      <th bgcolor="#feaf3f">Sale Price</th>
    </tr>
  </thead>
  <tbody>
    <tr id="tr">
      <td id="Item"></td>
      <td id="Price"></td>
      <td id="salePrice"></td>
    </tr>
  </tbody>
</table>

【问题讨论】:

  • 一开始就不查询数据库中的那些条目不是更容易吗?

标签: javascript html loops


【解决方案1】:

尝试以下方法:

var rowTag = document.getElementsByTagName("TD")
if(rowTag.textContent == "null"){
  rowTag.parentNode.removeChild()
}

【讨论】:

  • 它的document.getElementsByTagName,而不仅仅是getElementsByTagName,它会返回一个元素集合,所以rowTag.textContent 不起作用
  • 是的,我注意到一个错字。你也可以进一步定制,我的方法只是一个建议。
【解决方案2】:

首先你以错误的方式使用&lt;col&gt;标签,你需要使用&lt;colgroup&gt;作为它们的父标签并将它们放在&lt;thead&gt;标签之外。要删除空行,您应该使用 jQuery,然后您需要遍历行,如果第一列为空,则使用 td:first-child 选择器将其删除。看看sn-p。

$("#ex-table tbody tr").each(function() {
  var html = $(this).find("td:first-child").html();
  if (html === 'null') {
    $(this).remove()
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-striped" id="ex-table">
  <colgroup>
    <col width="120">
    <col width="120">
    <col width="120">
  </colgroup>

  <thead class="thead-inverse">
    <tr>
      <th bgcolor="#feaf3f">Item</th>
      <th bgcolor="#feaf3f">Price</th>
      <th bgcolor="#feaf3f">Sale Price</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td id="Item">null</td>
      <td id="Price">50</td>
      <td id="salePrice">60</td>
    </tr>
    <tr id="tr">
      <td id="Item">2</td>
      <td id="Price">60</td>
      <td id="salePrice">70</td>
    </tr>
  </tbody>
</table>

【讨论】:

  • 你忘了说上面是一个 jQuery 解决方案
  • 然而,关于应该使用 jQuery 的说法并不完全正确,因为纯 JavaScript 可以完成这项工作(同样简单)
  • 我建议更好的方法,因为使用 jQuery,您可以用更少的代码轻松完成任何应用程序所需的许多其他操作
  • 我们不知道 OP 是否需要进行许多其他操作,以及他是否认为通过应用性能来支付这种便利是可行的
  • 我不能说其他的事情,但是我针对这个问题发布的解决方案比纯javascript更准确,代码更少,而且我没有强迫用户使用jQuery,我'刚刚建议他/她使用它,如果他/她有任何问题,他/她可以评论它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-08
  • 2023-04-09
  • 2011-07-07
  • 2016-02-09
  • 2011-09-11
相关资源
最近更新 更多