js 表格操作----添加刪除


js 表格操作----添加刪除

書名:<input type="text" id="name">	
價格:<input type="text" id="price">	
			<button onclick="add()">添加</button>
			<table id="table" width="800" border="1">
				<tr>
					<td>書名</td>	
					<td>價格</td>
					<td>操作</td>			
				</tr>
				<tr>
					<td>遠方的美好</td>	
					<td>99</td>
					<td><button onclick="del(this)">刪除</button></td>			
				</tr>
				<tr>
					<td>精通javascript</td>	
					<td>99</td>
					<td><button onclick="del(this)">刪除</button></td>			
				</tr>
			</table>
		<script>
			function del(e){
				var tr = e.parentElement.parentElement;
				//獲取tr button的父親的父親
				var index = tr.rowIndex;
				//獲取是第幾行
				var table = document.getElementById("table");
				//獲取table
				table.deleteRow(index);
				//table刪除第index行
			}
			function add(){
				var table = document.getElementById("table");
			}
			//獲取table
				var name = document.getElementById("name");
				//獲取名稱
				var price = document.getElementById("price");
				//獲取價格
				var tr = table.insertRow(1);
				//插入到表格的第二行
				var td1 = tr.insertCell(0);
				//插入列
				var td2 = tr.insertCell(1);
				var td3 = tr.insertCell(2);
				td1.innerHTML= name.value;
				//設置列的內容
				td2.innerHTML= "¥"+price.value;
				td3.innerHTML= '<button οnclick="del(this)">刪除</button>';
				price.value='';//清空價格input的內容
				name.value='';//清空書名input的內容
		</script>


免責聲明!

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



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