有时候根据设计的需要,页面显示的元素并不固定,而是根据用户的意愿动态的增加。
本文将教你如何使用JavaScript动态创建HTML元素。
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
.d1{
background-color:black;
width:100px;
height:100px;
}
</style>
<script language="JavaScript">
function createDiv()
{
var a=document.createElement("div");
a.id=1;
a.className="d1";
document.body.appendChild(a);
}
function createInput()
{
var a=document.createElement("input");
a.value="sun";
document.body.appendChild(a);
}
</script>
</head>
<body>
<h1>动态创建HTML元素</h1>
<input type="button" value="创建input" οnclick="createInput();"/><br>
<input type="button" value="创建DIV" οnclick="createDiv();"/><br>
</body>
</html>