<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>访问器属性、获取dom元素</title>
</head>
<body>
<ul class="list">
<li class="item">item1</li>
<li class="item">item2</li>
<li class="item">item3</li>
<li class="item">item4</li>
<li class="item">item5</li>
</ul>
<script>
// 1. 理解访问器属性原理与应用场景,并实例演示
// 访问器属性将方法伪装成属性,可对引用设置对象属性进行简化操作
let classmate = {
data: {
id: 1,
age: 18,
},
getInfo() {
return `编号${this.data.id}的同学,年龄是${this.data.age}岁`;
},
setInfo(id, age) {
this.data.id = id;
if (age > 200) {
console.log("请不要输入妖怪");
} else {
this.data.age = age;
}
},
};
console.log(classmate.getInfo());
classmate.setInfo(666, 999);
console.log(classmate.getInfo());
classmate.setInfo(666, 150);
console.log(classmate.getInfo());
// 应用访问器属性
let classmates = {
data: {
id: 10086,
age: 18,
},
get info() {
return `编号${this.data.id}的同学,年龄是${this.data.age}岁`;
},
set info(info) {
this.data.id = info.id;
if (info.age > 200) {
console.log("请不要输入妖怪");
} else {
this.data.age = info.age;
}
},
};
console.log(classmates.info);
classmates.info = {
id: 10010,
age: 100,
};
console.log(classmates.info);
// 2. 实例演示获取dom元素的二个重要方法
// 1.利用queryselect获取元素
const item = document.querySelectorAll(".item");
console.log(item);
for(let i=0;i<item.length;i++){
item[i].style.color = "blue";
}
// 2.直接获取dom唯一元素节点
const head = document.title;
console.log(head);
</script>
</body>
</html>