访问器属性原理与获取DOM元素实践
访问器属性原理
先写一个常规的对象
/ /设置一个常规的类let userInfo={data:{name:'Jason',birthday:[2000,12,04],height:'1.75m',weight:'70kg'},// 获取姓名getName(){return this.data.name;},// 修改姓名ChangeName(name){if (name.length <= 20 ){this.data.name=name;}else{console.log('名字过长')}},// 获取年龄getAge(){return (2022-this.data.birthday[0])},// 获取身高getHeight(){return `${this.data.height[0]}${this.data.height[2]}${this.data.height[3]} cm`},// 修改身高SetHeight(height){return this.data.height=height;}}// 打印属性console.log(userInfo.data)console.log(userInfo.getAge())console.log(userInfo.getName())userInfo.SetHeight('1.80');console.log(userInfo.getHeight())userInfo.ChangeName('Authur')console.log(userInfo.getName())console.log(userInfo.data)
效果:

将对象方法改写成访问器属性
// 设置一个常规的类let userInfo={data:{name:'Jason',birthday:[2000,12,04],height:'1.75m',weight:'70kg'},// 获取姓名// getName(){// return this.data.name;// },// 改写get Name(){return this.data.name;},// 修改姓名// ChangeName(name){// if (name.length <= 20 ){// this.data.name=name;// }else{// console.log('名字过长')// }// },// 改写set Name(name){if (name.length <= 20 ){this.data.name=name;}else{console.log('名字过长')}},// 获取年龄get Age(){return (2022-this.data.birthday[0])},// 获取身高get Height(){return `${this.data.height[0]}${this.data.height[2]}${this.data.height[3]} cm`},// 修改身高set Height(height){return this.data.height=height;}}// 打印属性console.log(userInfo.data);console.log(userInfo.Name);console.log(userInfo.Age);console.log(userInfo.Height);userInfo.Height='1.88';userInfo.Name='Authur';console.log(userInfo.data);console.log(userInfo.Name);console.log(userInfo.Age);console.log(userInfo.Height);
改写后效果不变:

获取DOM元素
DOM概念:DOM (Document Object Model) 译为文档对象模型,是 HTML 和 XML 文档的编程接口。也就是说把文档编译成了一个对象模型,例如我们写的html文件实际上是一个文档文件,通过我们的浏览器把它编译成了一个对象模型,这个模型就是document对象。
生成一个html
<ul class="list"><li class="item"><button class="click">点我</button></li><li class="item"><button class="click">点我</button></li><li class="item"><button class="click">点我</button></li><li class="item"><button class="click">点我</button></li><li class="item"><button class="click">点我</button></li><li class="item"><button class="click">点我</button></li><li class="item"><button class="click">点我</button></li></ul>
1、如何获取文档对象
console.dir(document);
效果:

2、如何拿到类名为click的button标签组
// querySelectorAll(selector):返回一组元素// 这里将返回所有class为’click‘的标签console.dir(document.querySelectorAll('.click'))
效果:

这里传回的是一个数组,我们用常量来接收这个数组,就可在js中对button按钮进行设置
3、在js中对button标签进行样式设置
const button = document.querySelectorAll('.click')for (let i =0 ;i < button.length;i++){button[i].style.width='800px';button[i].style.margin='10px';}
效果:
