日期:2014-05-16  浏览次数:20347 次

DOM & JS DIV层操作__创建,指定删除,全部删除
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Untitled Document</title>
		<script src="temp.js" type="text/javascript"></script>
	</head>
	<body>
		<div>
			<span>
				<input type="text" id="text" name="mytest"/>				
			</span>			
			<span>
				<input type="submit" value="add" id="submit" onclick="addDIV(document.getElementById('text').value);"/>				
			</span>
			<span>
				<input type="submit" value="delete" id="submit" onclick="deleteDIV(document.getElementById('text').value);"/>				
			</span>
		   <span>
				<input type="submit" value="delete" id="submit2" onclick="deleteAllDIV();"/>				
			</span>
		<div>
			male<input type="radio"  name="nametest" value="good" checked="checked"/>
			female<input type="radio"  name="nametest" value="bad" />
		</div>
		<div>
			temp1<input type="checkbox"  name="nametest2" value="temp1" checked="checked"/>
			temp2<input type="checkbox"  name="nametest2" value="temp2" />
		</div>
		<div id="add">
			
		</div>
	</body>
</html>

?

function addDIV (addText) {
 /*创建新层*/  
 var div_view=document.createElement("div"); 
 var text = document.getElementById("add");
	div_view.id=addText;
	div_view.innerText=addText;
	text.appendChild(div_view);
}

function deleteDIV (id) {
 /*删除一个层*/ 
 var temp = document.getElementById(id);
 temp.parentNode.removeChild(temp);
}

function deleteAllDIV(){
    /*删除所有附加层*/
    var parent = document.getElementById("add");
	//这里因为childNodes节点会动态变下标,所以用0的index实现全部删除
    for (var i = 0, length= parent.childNodes.length; i < length; i++){
		parent.removeChild(parent.childNodes[0]);
	};
}