删除表中的最后一行时显示警报窗口

Display alert window when last row from table gets deleted

本文关键字:一行 显示 窗口 最后 删除      更新时间:2023-09-26

我有一个表,可以在其中动态添加和删除行。这是我为完成而写的代码

<SCRIPT TYPE="text/javascript">
var count = "2";
function addRow(in_tbl_name)
{
var tbody = document.getElementById(in_tbl_name).getElementsByTagName("TBODY")[0];
// create row
var row = document.createElement("TR");
// create first col
var td1 = document.createElement("TD")
var strHtml1 = "This is the line number " + count;
td1.innerHTML = strHtml1.replace(/!count!/g,count);
// create second col
var td2 = document.createElement("TD")
var strHtml2 = "<INPUT TYPE='Button' CLASS='Button' onClick='delRow()' VALUE='Delete Row'>";
td2.innerHTML = strHtml2.replace(/!count!/g,count);
// append data to row
row.appendChild(td1);
row.appendChild(td2);
// add to count variable
count = parseInt(count) + 1;
// append row to table
tbody.appendChild(row);
}
function delRow()
{
var current = window.event.srcElement;
//here we will delete the line
while ( (current = current.parentElement)  && current.tagName !="TR");
     current.parentElement.removeChild(current);
}
</SCRIPT>

这是HTML元素的代码。

<div id="container">
<INPUT TYPE="Button" onClick="addRow('tblPets')" VALUE="Add Row">
<TABLE ID="tblPets" border="1" STYLE="border width:1 orange dashed;background color:#F0E68C;table-row width:2;">
    <TR><TD>Frist col</TD><TD>Second col</TD></TR>
    <TR><TD>This is the line number 1.</TD><TD><INPUT TYPE="Button" CLASS="Button" onClick="delRow()" VALUE="Delete Row"></TD></TR>
</TABLE>
</div>

到目前为止一切都很好。我想不出如何完成的最后一步是,当我从表中删除每一行时,会出现一条警告消息,上面写着alert("Table is empty");

我该怎么做?如何使我的delRow()函数了解表何时完全为空?

如有任何帮助,我们将不胜感激。

你可以试试这个

if(document.getElementById("myTable").rows.length == 1)
  alert("this is last row ")
else if (document.getElementById("myTable").rows.length == 0)
  alert("table is empty now ")

实际上,这是我的一个愚蠢的问题。我只是用我的计数变量来做的。。

用这个简单的if

if ( count == 1 )
    alert("Table is empty");