1. 在JS中如果使用var
定义循环变量,会导致变量提升,也就是直接使循环变量为最后一个数
所以我们使用let
对循环变量定义
2.除了for循环 我们也可以使用 let i in 数组
的方式实现循环
3.使用循环返回对象中的属性值
for(var i in data[0])
{
console.log(i); // 返回对象属性名
console.log(data[0][i]); // 返回对象属性内容
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> 人物表格 </title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="fatherbox">
<ul class="servelist">
<li>商品介绍</li>
<li>规格与包装</li>
<li>售后与保障</li>
<li>商品评价</li>
</ul>
<div class="showarea"></div>
</div>
<!-- JS 代码位置 -->
<script>
var li_list = document.querySelector(".servelist");
var showarea = document.querySelector(".showarea")
var li = li_list.querySelectorAll("li");
for(let i = 0;i < li.length; i++)
{
li[i].onclick = function() {
for(let j = 0;j < li.length;j++){
li[j].className = "";
showarea.className = "showarea current" + i;
}
}
}
</script>
</body>
</html>
CSS
* {
padding: 0px;
margin: 0px;
}
.fatherbox {
width: 500px;
height: 100px;
margin: 100px auto;
}
.servelist li {
float: left;
background-color: orange;
padding: 20px;
list-style-type: none;
}
.servelist li:hover {
background-color: grey;
cursor: pointer;
}
.showarea {
float: left;
width: 448px;
height: 300px;
background-color: pink;
}
.current0 {
background-color:red;
}
.current1 {
background-color:skyblue;
}
.current2 {
background-color:green;
}
.current3 {
background-color:purple;
}