1. 程式人生 > >用js操作table(tr,td) (包括TD內容的隱藏,背景顏色和字型的設定)

用js操作table(tr,td) (包括TD內容的隱藏,背景顏色和字型的設定)

function messageSort() {  --函式名
var message=document.getElementById("message").value; --新增的內容(下面有對應的html)
if(name == "" ) return; --如果新增為空,返回
var row = document.createElement("tr"); //建立tr的
row.setAttribute("id", name); --設定row的屬性.
var cell = document.createElement("td");//建立td
cell.appendChild(document.createTextNode(name));//td裡注入文字


row.appendChild(cell);//將TD注入TR

var deleteButton = document.createElement("input"); //這部分是新增刪除button按鈕
deleteButton.setAttribute("type", "button");
deleteButton.setAttribute("value", "刪除");
deleteButton.onclick = function () { deleteSort(name); };
cell = document.createElement("td");
cell.appendChild(deleteButton);//注入按鈕

row.appendChild(cell);//將TD注入TR
document.getElementById("sortList").appendChild(row);//將TR注入到相應地方(sortList可以看下面html)
var cell5 = document.createElement("td");

cell.style.background="#ffffff";//背景顏色設定

row1.style.color="#ffffff"; //字型顏色設定
cell5.style.display = "none" ;   //ie不支援setAttribute("style", "display:none");

// <td  style="display:none"  >dd</td> 直接寫TD是這樣..
cell5.appendChild(document.createTextNode(zdid));
row.appendChild(cell5);

}
// 刪除內容
function deleteSort(id) {//這個函式為上面的刪除button呼叫的
var rowToDelete = document.getElementById(id);
var sortList = document.getElementById("sortList");
sortList.removeChild(rowToDelete);
}
</script>
</head>
<body>
<table border="0" cellspacing="0" width="400" bgcolor="#f5efe7">
<tr>
    <td height="20">增加內容:</td>
    <td><input id="message" type="text"></td>
    <td><a href="javascript:messageSort();">新增</a></td>
</tr>
</table>
<table border="1" width="400">
<tr>
    <td height="20" align="center">內容:</td>
    <td>操作</td>
</tr>
<tbody id="sortList"></tbody>
</table>
</body>
</html>