元素创建的三种方式:
- document.write("标签的代码及内容");
- 对象.innerHTML="标签及代码";
- document.createElement("标签的名字");
document.write()创建元素,缺陷:如果是在页面加载完毕后,此时通过这种方式创建元素,那么页面上存在的所有的内容全部被清除。
比如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" id="btn" value="创建文本" />
<script>
document.getElementById("btn").onclick=function () {
document.write("<p>这是一个p</p>");
};
</script>
</body>
</html>
使用innerHTML创建元素:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" id="btn" value="创建文本" />
<div id="dv"></div>
<script>
document.getElementById("btn").onclick=function () {
document.getElementById("dv").innerHTML="<p>我是一个p</p>";
};
</script>
</body>
</html>
createElement创建元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" id="btn" value="创建p" />
<div id="dv"></div>
<script>
document.getElementById("btn").onclick=function () {
var pobj=document.createElement("p");
pobj.innerText="我是一个p";
document.getElementById("dv").appendChild(pobj);
};
</script>
</body>
</html>
为元素绑定多个事件
使用下面的方法不能绑定多个事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" id="btn" value="发聊天" />
<script>
document.getElementById("btn").onclick=function () {
console.log("Hello");
};
document.getElementById("btn").onclick=function () {
console.log("Hi");
};
document.getElementById("btn").onclick=function () {
console.log("你好");
};
document.getElementById("btn").onclick=function () {
console.log("再见");
};//只输出再见
</script>
</body>
</html>
所以使用addEventListener
//1 对象.addEventListener("事件类型",事件处理函数,false);--谷歌和火狐支持,IE8不支持
//2 对象.attachEvent("有on的事件类型",事件处理函数)--谷歌不支持,火狐不支持,IE8支持
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="button" id="btn" value="发聊天" />
<script>
document.getElementById("btn").addEventListener("click",function () {
console.log("你好啊");
},false);
document.getElementById("btn").addEventListener("click",function () {
console.log("Hello");
},false);
document.getElementById("btn").addEventListener("click",function () {
console.log("再见");
},false);
</script>
</body>
</html>