Jquery 實現表格動態增加一行,刪除一行


需求是要實現表格的動態增加與刪除,並且保留標題行和首行,找了半天jq插件,沒找到合適的,所以自己寫了個demo

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<style type="text/css">
	table.table input{ /*可輸入區域樣式*/ 
width:100%; 
height: 100%;
 

border:none; /* 輸入框不要邊框 */ 
font-family:Arial; 
} 
</style>
</head>
<body>
<br>

<table class="table" border="1">
	<thead>
	<tr>
		<th>檢項</th>
		<th>厚度</th>
		<th>光度</th>
		<th>外觀</th>
	</tr>
	</thead>
	<tbody>
	<tr id="a">
		
		<td class="td"></td>
		<td><input type="" name=""></td>
		<td><input type="" name=""></td>
		<td><input type="" name=""></td>
		
	</tr>
	<tr>
		
		<td class="td"></td>
		<td><input type="" name=""></td>
		<td><input type="" name=""></td>
		<td><input type="" name=""></td>
		 
	</tr>
		
	</tbody>
	
</table>

<button onclick="fun()">增加一行</button>
<button onclick="del()">刪除一行</button>

<script type="text/javascript">                   //前面的序號1,2,3......
	var i = 1;
	$(".td").each(function(){
		$(this).html(i++);
	})


	function fun(){
		var $td = $("#a").clone();       //增加一行,克隆第一個對象
		$(".table").append($td);
		var i = 1;
		$(".td").each(function(){       //增加一行后重新更新序號1,2,3......
		$(this).html(i++);
		})
		$("table tr:last").find(":input").val('');   //將尾行元素克隆來的保存的值清空
	}

	function del(){
		$("table tr:not(:first):not(:first):last").remove();      //移除最后一行,並且保留前兩行
	}
</script>
 </body>	
</html>

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM