2010年12月21日 星期二

javascript 動態增減減表格

雖然有查到許多資料像 document.getElementById("").RemoveChild() 的方式,不過是了半天是不出來,所以就用簡單的方式 修改 element 裡的 innerhtml 來達成我的目標


code 如下


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />



<title>Sample</title>

<script type="text/javascript">


var ItemCount=0;

var temp=new Array();


/*
Add Item field

*/

function addItem()
{

eval("document.getElementById('addButton"+ItemCount+"').style.visibility = \"hidden\";");
if(ItemCount!=0)
eval("document.getElementById('deleteButton"+ItemCount+"').style.visibility = \"hidden\";");



temp[ItemCount] = document.getElementById('ItemList').innerHTML;
ItemCount++;

document.getElementById('ItemList').innerHTML +=
"<br> <br> Item Id : <input name=\"ItemId"+ ItemCount +"\" type=\"text\" /> " +

"Item Aliases : <input name=\"ItemAliases"+ItemCount +"\" type=\"text\" /> " +

//<button id="addButton0" onclick="addItem()">ADD </button>

"<button id=\"addButton"+ ItemCount+ "\" onclick=\"addItem()\"> ADD</button>" +

"&nbsp; <button id=\"deleteButton"+ ItemCount+ "\" onclick=\"deleteItem()\"> delete</button>"


;



}


function deleteItem(){


ItemCount--;
document.getElementById('ItemList').innerHTML = temp[ItemCount];
// Set null
temp[ItemCount]=null;
//alert(ItemCount);
eval("document.getElementById('addButton"+ItemCount+"').style.visibility = \"visible\";");
if(ItemCount!=0)
eval("document.getElementById('deleteButton"+ItemCount+"').style.visibility =\"visible\";");

}




</script>


</head>
<body>



<div id="ItemList">
Item Id : <input name="ItemId0" type="text" />
Item Aliases : <input name="ItemAliases0" type="text" />

<button id="addButton0" onclick="addItem()">ADD </button>


</div>


</body>
</html>








我的範例, 裡面點 open 可以直接看
https://docs.google.com/leaf?id=0B_JOf_Tyv_f6ODI5M2QyZTgtNGU2ZC00NmQzLWIwMjktMWNmMDQxZjRkZjdm&sort=name&layout=list&num=50

沒有留言: