一篇案例让你了解js如何操作表格元素(表格中添加内容行)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript">
			window.onload = function(){
				//用户输入内容后点击添加,添加一行
				var ptS = document.getElementsByTagName('input');
				var tab = document.getElementsByTagName('table')[0];
				ptS[3].onclick = function(){
					var name = ptS[0].value;
					var sex = ptS[1].value;
					var age = ptS[2].value;
					//创建tr行
					var tr = document.createElement('tr');
					//循环创建td
					for(var i=0; i<4; i++){
						var td = document.createElement('td');
						//td添加到tr
						tr.appendChild(td);
					}
					//设置td内容
					tr.cells[0].innerText = tab.tBodies[0].rows.length+1;
					tr.cells[1].innerText = name;
					tr.cells[2].innerText = sex;
					tr.cells[3].innerText = age;
					//将tr追加到tbody中显示
					tab.tBodies[0].appendChild(tr);
				}
			}
		</script>
	</head>
	<body>
		<input type="text" placeholder="请输入姓名">
		<input type="text" placeholder="请输入性别">
		<input type="text" placeholder="请输入年龄">
		<input type="button" value="添加">
		<table width="500" border="1">
			<thead>
				<tr>
					<td>id</td>
					<td>姓名</td>
					<td>性别</td>
					<td>年龄</td>
				</tr>
			</thead>
			<tbody>
				<!-- <tr>
					<td>1</td>
					<td>tom</td>
					<td>男</td>
					<td>18</td>
				</tr>
				<tr>
					<td>2</td>
					<td>jack</td>
					<td>男</td>
					<td>20</td>
				</tr>
				<tr>
					<td>3</td>
					<td>rose</td>
					<td>女</td>
					<td>18</td>
				</tr> -->

			</tbody>
			<tfoot></tfoot>
		</table>
	</body>
</html>

 

posted @ 2023-01-02 01:38  JackieDYH  阅读(109)  评论(0编辑  收藏  举报  来源