我有一个表,我在其中动态添加和删除行。这是我为此编写的代码
<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()
函数了解表格何时完全为空?
任何帮助将不胜感激。