利用JavaScript动态添加Div的方式有很多,一下是个比较常用的。
一、在一个Div前添加Div
<html>
<body>
<div id="a">
<div id="a1">1</div>
<div id="a2">2</div>
</div>
<a href="javascript:addDiv();">test</a>
</body>
<script type="text/javascript">
function addDiv(){
var newNode=document.createElement("div");
newNode.setAttribute("id","a3");
var txtNode=document.createTextNode("3");
newNode.appendChild(txtNode);
document.getElementById("a").insertBefore(newNode,document.getElementById("a2"));
alert(document.getElementById("a").innerHTML)
}
</script>
</html>
二、动态添加Div,并在Div上添加事件
<html>
<body>
<a href="javascript:aa();">text</a>
</body>
</html>
<script language=javascript>
var divId=1;
//动态生成单纯的div
function CreateOuterDiv()
{
var obj=document.createElement("div");
obj.id="myDiv"+divId;
divId++;
obj.style.border="1px solid #000000";
obj.style.height="30px";
obj.style.width="200px";
obj.style.filter="alpha(opacity=70)";
obj.style.margin="10px";
obj.style.cursor="hand";
obj.algin="center";
//obj.innerHTML="<a href='#"+obj.id+"'>ssssssssss</a>";
obj.innerText="sssssss";
document.body.appendChild(obj);
document.getElementById(obj.id).οnclick=function(){aa();};
}
function aa()
{
CreateOuterDiv();//alert();
}
</script>
三、动态添加Div,并删除某个Div
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<script type="text/javascript">
var a=0;
function add(){
var o=document.getElementById("PhotoLabel");
var div=document.createElement("div");
div.id = div.name = "d"+ a;
div.innerHTML=o.innerHTML.replace(//{0/}/ig,a);
document.getElementById("addPhotoLabel").appendChild(div);
//document.write(document.getElementById("addPhotoLabel").innerHTML);
alert(document.getElementById("addPhotoLabel").innerHTML);
a++;
}
//window.onload = function(){add();}
function deleteDiv(){
var oDiv= document.getElementById("d2");
document.getElementById("addPhotoLabel").removeChild(oDiv);
}
</script>
<body>
<div id="PhotoLabel">
safasfdgdag
<a>aasscc</a>
</div>
<div id="addPhotoLabel"></div>
<a href="javascript:add();"><span style="font-size: 15px">增加</span></a>
<a href="javascript:deleteDiv();"><span style="font-size: 15px">删除第二个</span></a>
</body>
</html>