js 動態增刪table

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>動態增刪表格</title>
</head>

<body>
<table border=1 id="Table1" style="text-align:center">
  <tr>
    <td width="84">姓名</td>
    <td width="35">年齡</td>
    <td width="44">性別</td>
    <td width="84">電話</td>
    <td width="84">學歷</td>
    <td width="68"> </td>
  </tr>
</table>
<br/>
<input type="button" value="增加一行" οnclick="javascript:addRow()">
<script language="javascript">
    var row_index=0;
	//建立一個函數addRow()用於建立新的一行
	function addRow(){
		row_index++;
		//新增一行賦給變量new_row,表示建立了一個tr
		var new_row=Table1.insertRow(Table1.rows.length);
		//給tr元素設置屬性,參數1表示屬性名(id),參數2表示該屬性的值
		new_row.setAttribute("id", "row"+row_index);
		//新增一列賦給變量new_col,表示建立了一個td
		var new_col=new_row.insertCell(0);
		//給列裏賦值
		new_col.innerHTML="<input type='text'name='name"+row_index+"'size=10>";
		var new_col=new_row.insertCell(1);
		new_col.innerHTML="<input type='text'name='age"+row_index+"'size=2>";
		var new_col=new_row.insertCell(2);
		new_col.innerHTML="<select name=‘sex"+row_index+"'><option value='男'>男</option><option value='女'>女</option></select>";
		var new_col=new_row.insertCell(3);
		new_col.innerHTML="<input type='text' name='phone"+row_index+"' size=10>";
		var new_col=new_row.insertCell(4);
		new_col.innerHTML="<input type='text' name='spec"+row_index+"' size=10>";
		var new_col=new_row.insertCell(5);
		new_col.innerHTML="<input type='button' value='刪除此行' οnclick=\"delete_row('row"+row_index+ "')\">";
		}
		function delete_row(rname){
			//函數delete_row用於刪除一行
			var i;
			i=Table1.rows(rname).rowIndex;
			if (confirm('確定刪除第'+i+'行?'))
			Table1.deleteRow(i);
			}
	</script>
</body>
</html>

js動態增刪網頁表格 - 雲代碼 http://yuncode.net/code/c_50bb4be8e592236

發佈了61 篇原創文章 · 獲贊 13 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章