簡體   English   中英

使用 Javascript 從 HTML 表中刪除空行

[英]Deleting null rows from HTML table with Javascript

我有一個從數據庫中提取的 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>

請嘗試以下操作:

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

如果您碰巧是從不受控制的后端獲取數據(因此您無法查詢那些不需要的條目),則可以使用document.querySelectorAll('#ex-table tbody td:nth-child(1)')來獲取所有第一列單元格document.querySelectorAll('#ex-table tbody td:nth-child(1)')進行迭代,並在將textContent匹配為null時刪除整個行.parentNode.remove()

 document.getElementById('cleanup').addEventListener('click', () => [...document.querySelectorAll('#ex-table tbody td:nth-child(1)')].forEach(td => td.textContent == 'null' ? td.parentNode.remove() : true)); 
 <table id="ex-table"><thead><tr><th>Item</th><th>Price</th><th>Sale Price</th></tr></thead><tbody><tr><td>1</td><td>null</td><td>33</td></tr><tr><td>2</td><td>38</td><td>50</td></tr><tr><td>null</td><td>null</td><td>null</td></tr><tr><td>3</td><td>41</td><td>54</td></tr><tr><td>4</td><td>13</td><td>17</td></tr><tr><td>5</td><td>2</td><td>3</td></tr></tbody></table><button id="cleanup">Clean</button> 

首先,您以錯誤的方式使用<col>標簽,您需要使用<colgroup>作為它們的父級並將它們放在<thead>標簽之外。 要刪除空行,您應該使用 jQuery,然后您需要遍歷行,如果第一列為空,則使用td:first-child選擇器將其刪除。 看看片段。

 $("#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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM