<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>dom的綜合練習</title>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312"/>
<style type="text/css">
<!-- .txtStyle{ font-weight: bold; font-size:20px; text-align:center;height:30;}
table{width:500px; background-color:#99ccff; bgcolor:#000000;}
.btnStyle{width:80; height:30}-->
</style>
<script type="text/javascript">
function addSort() {
var txtInput = document.getElementById("txt");
if (txtInput.value == "") {
alert("請輸入分類!");
return;
}
//檢測分類名是否已經存在 根據<td>中的tag屬性來找“類型”文本
if(txtInput.value!=""){
var txtTable = document.getElementById("sortList");
var txtCells = txtTable.getElementsByTagName("tr"); //爲tr數組
var txtTr="";
for (var i = 0; i < txtCells.length; i++) {
txtTr = txtCells[i].childNodes[0].innerHTML; //第一個td的文本
if (txtTr == txtInput.value) {
alert("已經有該分類!,請重新填寫");
txtInput.value = "";
return;
}
// else {document.write("你妹");}
}
}
//==================================================
//添加一個類別單元格代碼
var row = document.createElement("tr");
row.setAttribute("id", txt);
row.bgColor = "#99FF99";
var cell = document.createElement("td");
cell.bgColor = "#6699cc";
var txtNode = document.createTextNode(txtInput.value);
cell.appendChild(txtNode);
row.appendChild(cell);
//==================================================
//添加一個 按鈕單元格代碼
cell = document.createElement("td");
var delbtn = document.createElement("input");
delbtn.setAttribute("type", "button");
// delbtn.setAttribute("tag","txt");//加入一個區分標記來識別是分類文本
delbtn.setAttribute("value", "刪除");
delbtn.setAttribute("class", "btnStyle");
delbtn.onclick = function () { delSort(txt); }
cell.appendChild(delbtn);
row.appendChild(cell);
document.getElementById("sortList").appendChild(row);
txtInput.value = "";
}
function delSort(id) {
if (id != null) {
var rowToDel = document.getElementById(id);
var sortList = document.getElementById("sortList");
sortList.removeChild(rowToDel);
}
}
</script>
</head>
<body>
<table border="1px" bgcolor="">
<tbody class="txtStyle">
<tr class="txtSyle">
<td class="txtSyle" colspan="3">
分類管理
</td>
</tr>
<tr height="30">
<td width="179">請輸入分類名稱:</td>
<td width="179"><input id="txt" type="text" size="20" height="30"/></td>
<td width="120"><input class="btnStyle" type="button" οnclick="addSort()" size="20" height="30" value="添加"/></td>
</tr>
<tr>
<td class="txtStyle" colspan="3">已添加的分類</td>
</tr>
</tbody>
</table>
<table border="1">
<tr height="30">
<td width="363">分類名稱</td>
<td>操作</td>
</tr>
<tbody id="sortList"></tbody>
</table>
</body>
</html>