使用javascript检查我的html表是否为空

时间:2019-01-29 13:39:43

标签: javascript html css

如何检查我的html表是否为空。请记住,下表必须被视为空表,因为除标题外没有其他行。

<table style="float: left;text-align: center;" id="Table1"">
     <th style="width: 11%;">Item Id</th>
     <th style="width: 44%;">Item Name</th>
     <th style="width: 11%;">Quantity</th>
     <th style="width: 18%;">Trade Price</th>
     <th style="width: 16%;">Price</th>
     <th style="width: 7%;" id="non-printable">Delete</th>
</table>

这些标题是固定的,我正在使用javascript生成行。如果表为空,我必须重置我的JavaScript计数器。如何使用javascript或jquery检查表是否为空?

当我使用javascript添加行时,我正在增加另一个计数器。

5 个答案:

答案 0 :(得分:2)

您可以计算表主体中的行。相应地设置您的桌子。

console.log(document.querySelectorAll('#Table1 tbody tr').length); // 0

document.querySelector('#Table1 tbody').appendChild(document.createElement('TR'));

console.log(document.querySelectorAll('#Table1 tbody tr').length); // 1
<table style="float: left;text-align: center;" id="Table1">
  <thead>
    <th style="width: 11%;">Item Id</th>
    <th style="width: 44%;">Item Name</th>
    <th style="width: 11%;">Quantity</th>
    <th style="width: 18%;">Trade Price</th>
    <th style="width: 16%;">Price</th>
    <th style="width: 7%;" id="non-printable">Delete</th>
  </thead>
  <tbody>
  </tbody>
</table>

答案 1 :(得分:1)

我在每一行的计数器中递减并删除。如果为零,则另一个计数器将设置为零。

function deleteRow(id)
{
    var priceID="price"+id;
    //alert(priceID);
    var value=document.getElementById(priceID).innerHTML;
    //alert(value);
    var totalWithoutDiscount1=document.getElementById("Total_without_discount").value;
    var newTotal=(parseFloat(totalWithoutDiscount1)-parseFloat(value)).toFixed(2);
    //alert(newTotal);
    document.getElementById("Total_without_discount").value=newTotal;
    document.getElementById("Table1").deleteRow(id-counter);
    document.getElementById("Table2").deleteRow(id-counter);
    count--;
    counter++;
    if(count==0)
    {
            counter=0;
            alert(counter);
    }
}

答案 2 :(得分:0)

您可以使用表的 length 属性来确定表中的行数。

var rows = $('#Table1').rows.length;

答案 3 :(得分:0)

如果要检查表是否为空,则需要检查行数是否为0。

if ($('#Table1 tr').length == 0) {
    //...do something here
}

答案 4 :(得分:0)

您知道一个表如果只包含一行(因为在表头周围动态添加了一行),则该表为空。因此,您可以尝试选择表中的所有行,并检查返回的集合的长度。如果长度小于或等于1,则说明该表为空。否则,如果它更大,那么您就知道它在表中有行。

请参见以下示例:

const isEmpty = document.querySelectorAll("#Table1 tr").length <= 1;
console.log(isEmpty);
<table style="float: left;text-align: center;" id="Table1">
  <th style="width: 11%;">Item Id</th>
  <th style="width: 44%;">Item Name</th>
  <th style="width: 11%;">Quantity</th>
  <th style="width: 18%;">Trade Price</th>
  <th style="width: 16%;">Price</th>
  <th style="width: 7%;" id="non-printable">Delete</th>
</table>