当表的最后一行被删除时显示警告窗口

时间:2013-11-21 13:02:13

标签: javascript html dynamic html-table dynamic-tables

我有一个表格,我在其中动态添加和删除行。这是我写的代码

<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()函数能够理解表何时变为空?

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:0)

你可以试试这个

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 ")

答案 1 :(得分:0)

实际上这对我来说是个愚蠢的问题..我只是用我的计数变量来做..

用这个简单的if

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