访问器属性与dom元素获取
作业标题:0712作业
作业内容:
- 实例演示”访问器属性”,例如商品金额计算。
- 实例演示dom元素的获取,遍历与增删,方法不限于课堂上提及的,更多的可查阅mdn手册。
访问器属性
<!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>访问器属性</title>
</head>
<body>
<script>
let test = {
data: {
tops: "童装",
numbers: 40,
price: 50,
},
set numbers(numbers) {
if (numbers > 0 && numbers != null) {
return (this.data.numbers = numbers);
}
console.log("请输入合法数据");
},
set price(price) {
if (price > 0 && price != null) {
return (this.data.price = price);
}
console.log("请输入合法数据");
},
get numbers() {
return this.data.numbers;
},
get price() {
return this.data.price;
},
get tops() {
return this.data.tops;
},
};
test.price = 40;
test.numbers = 10;
console.log(test.tops + "总价为:" + test.numbers * test.price);
</script>
</body>
</html>
dom元素的获取
<!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>
//使用css方式最直观的,学习成本最低的
// document.querySelectorAll(css选择器):返回满足条件的元素集合
const items = document.querySelectorAll(".list .item");
console.log(items);
//NodeList:节点列表集合,是一个类数组,系统专为它定义一个forEach()遍历接口
items.forEach((item) => (item.style.color = "red"));
//返回满足条件的元素集合第一个,常用来返回唯一元素
const first = document.querySelector(".list .item");
console.log(first);
//body
console.log(document.body);
//title
console.log(document.title);
</script>
<form action="" name="login" id="mylogin">
<input type="email" name="email" value="admin@php.cn" />
<button>提交</button>
</form>
<script>
let $ = (selectior) => document.querySelector(selectior);
console.log(($("body").style.background = "lightgreen"));
//表单获取的特殊性
console.log(document.forms.mylogin);
console.log(document.forms.login);
//此时,表单中的 input等控件的name属性,就可以直接当id用来获取当前的元素
console.log(document.forms.login.email.value);
</script>
</body>
</html>