1.document.write(“标签代码及内容”);
<body>
<input type="button" value="创建一个p" id="btn"/>原本的元素
<script src="common.js"></script>
<script>
document.getElementById("btn").onclick=function () {
document.write("<p>这是一个p</p>");
};
</script>
document.write()创建元素,缺陷:如果是在页面加载完毕后,此时通过这种方式创建元素,那么页面上存在的所有的内容全部被干掉
2.第二种方式创建元素: 对象.innerHTML=“标签代码及内容”;
<body>
<input type="button" value="创建一个p" id="btn" />
<div id="dv"></div>
<script>
//点击按钮,在div中创建一个p标签
document.getElementById("btn")..onclick=function () {
my$("dv").innerHTML="<p>窗前明月光,疑是地上霜,举头望明月,低头思故乡</p>";
};
</script>
</body>
3.第三种方式创建元素
创建元素:document.createElement(“标签名字”);
把元素追加到父级元素中
<body>
<input type="button" value="创建p" id="btn"/>
<div id="dv"></div>
<script>
document.getElementById("btn").onclick = function () {
//创建元素的
var pObj = document.createElement("p");
pObj.innerText="这是一个p";
//把创建后的子元素追加到父级元素中
my$("dv").appendChild(pObj);
};
</script>
</body>
动态创建列表
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title</title>
<style>
* {
margin: 0;
padding: 0;
}
ul {
list-style-type: none;
cursor: pointer;
}
div {
width: 200px;
height: 400px;
border: 2px solid red;
}
</style>
</head>
<body>
<input type="button" value="创建列表" id="btn"/>
<div id="dv"></div>
<script>
var kungfu = ["小猫", "小狗", "小兔", "小鸡", "小鸭", "小黑", "熊猫", "大象", "猴子", "老鼠"];
//点击按钮动态的创建列表,把列表加到div中
document.getElementById("btn").onclick = function () {
//创建ul,把ul立刻加入到父级元素div中
var ulObj = document.createElement("ul");
document.getElementById("dv").appendChild(ulObj);
//动态的创建li,加到ul中
for (var i = 0; i < kungfu.length; i++) {
var liObj = document.createElement("li");
//设置li中间的文字内容
liObj.innerHTML = kungfu[i];
ulObj.appendChild(liObj);
//为li添加鼠标进入事件
liObj.onmouseover = mouseoverHandle;
//为li添加鼠标离开事件
liObj.onmouseout = mouseoutHandle;
}
};
//此位置.按钮的点击事件的外面
function mouseoverHandle() {
this.style.backgroundColor = "red";
}
function mouseoutHandle() {
this.style.backgroundColor = "";
}
</script>
</body>
</html>