使用javascript操作table(表格)Dom,添加/删除一行

看代码吧…
主要三个方法是insertRow和insertCell,deleteRow

看代码吧…

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
<script type="text/javascript" language="javascript">
	function addCell(){
		oRow = document.getElementById("mytable").insertRow();//插入行
		for (var k=0;k<4;k++){
		var oCell = oRow.insertCell();//插入单元格
		if (k==0)
			oCell.innerHTML = "<input type='checkbox'/>";
		else
			oCell.innerHTML = document.getElementById("mytable").rows.length;
		}
	}
	function delRow(){
		for (var k=0; k<document.getElementById("mytable").rows.length; k++){
			var arow = document.getElementById("mytable").rows(k);//得到每一行
			var cb = arow.getElementsByTagName("input");
			if (cb[0].checked){
				document.getElementById("mytable").deleteRow(k);//删除第k行
				k--;
			}
		}
	}
	
	function selectAll(){
		for (var k=0; k<document.getElementById("mytable").rows.length; k++){
			var arow = document.getElementById("mytable").rows(k);
			var cb = arow.getElementsByTagName("input");
			if (!cb[0].checked){
				cb[0].checked = true;
			}
		}
	}

	function unSelectAll(){
		for (var k=0; k<document.getElementById("mytable").rows.length; k++){
			var arow = document.getElementById("mytable").rows(k);
			var cb = arow.getElementsByTagName("input");
			if (cb[0].checked){
				cb[0].checked = false;
			}
		}
	}
</script>
</head>

<body>
	<input type="button" onClick="addCell()" value="添加"/>
	<input type="button" onClick="delRow()" value="删除"/>
    <input type="button" onClick="selectAll()" value="全选">
    <input type="button" onClick="unSelectAll()" value="全不选">
    <table id="mytable"></table>
</body>
</html>
updatedupdated2024-11-302024-11-30