节点的增删改查
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.div1,.div2,.div3,.div4{
width: 300px;
height: 100px;
}
.div1{
background-color: green;
}
.div2{
background-color: yellow;
}
.div3{
background-color: rebeccapurple;
}
.div4{
background-color: deeppink;
}
</style>
</head>
<body>
<div class="div1">
<button onclick="add()">add</button>
hello div1
</div>
<div class="div2">
<button onclick="del()">del</button>
hello div2
</div>
<div class="div3">
<button onclick="change()">change</button>
<p>hello div3</p>
</div>
<div class="div4">hello div4</div>
<script>
###############增加节点######################
function change() {
var img=document.createElement("img");//<img src="">
//img.setAttribute("src","meinv.jpg");
img.src="meinv.jpg";
var ele=document.getElementsByTagName("p")[0];
var father=document.getElementsByClassName("div3")[0];
father.replaceChild(img,ele)
}
###############修改节点######################
function add() {
var ele=document.createElement("p");//<p></p>
ele.innerHTML="<h1>hello p</h1>";
//ele.innerText="<h1>hello p</h1>";
ele.style.color="red";
ele.style.fontSize="10px";
var father=document.getElementsByClassName("div1")[0];
father.appendChild(ele)
}
###############删除节点######################
function del() {
var father=document.getElementsByClassName("div1")[0];
var son=father.getElementsByTagName("p")[0];
father.removeChild(son)
}
</script>
</body>
</html>
利用JS绑定事件的两种方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p onclick="func(this)">hello</p>
<div>hello DIV</div>
<script>
// 绑定事件方式一
function func(self) {
console.log(self)
alert(1234)
}
// 绑定事件方式二
var ele=document.getElementsByTagName("div")[0]
ele.onclick=function () {
console.log(ele);
console.log(this);
// alert(6666)
}
</script>
</body>
</html>
JS的class属性
<script>
var ele=document.getElementsByTagName("div")[0];
# class的名称
console.log(ele.className);
# 以列表返回class中值
console.log(ele.classList[0]);
# 以列表返回class中值
console.log(ele.classList[1]);
# 向列表中增加元素
ele.classList.add("hide")
console.log(ele.className);
</script>
Event对象:封装了事件的信息
可以用来阻止事件传播
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" id="form1">
<input type="text" name="username">
<input type="submit" value="提交">
</form>
<script>
var ele=document.getElementById("form1");
ele.onsubmit=function (e) {
// console.log("hello")
alert(1234);
// 方式一 返回false
return false
// 方式二 preventDefault函数
//e.preventDefault()
}
</script>
</body>
</html>