<!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>Document</title>
<style>
* {
margin: 0;
/* 外边距 */
padding: 0;
/* 内边距 */
}
#box {
text-align: center;
/* 元素文本的水平对齐方式 */
margin-top: 100px;
}
li {
display: inline-block;
width: 20px;
height: 20px;
padding: 5px;
border: 1px solid #000;
line-height: 20px;
text-align: center;
/* cursor: pointer; */
cursor: pointer;
/* 设置光标 corsshair 十字*/
}
li.active {
background-color: #000;
color: white;
}
</style>
</head>
<body>
<div id="box">
<ul>
<li class="active">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
<script>
// this
// 在函数调用的时候才知道this的意思
// 同一个函数在不同的时候调用,this的意思也不同
// function clickHandler() {
// console.log(this)
// }
// // 直接调用函数,函数里面的this是window
// clickHandler()
// 我作为事件处理函数调用
// var li1 = document.querySelector('li')
// li1.onclick = function () {
// // 事件处理函数里面的this指向的是事件源
// console.log(this, 'this')
// }
// 给每个li都添加上点击事件
var liS = document.querySelectorAll('li')
// 循环给每个li添加点击事件
for (var i = 0; i < liS.length; i++) {
liS[i].addEventListener('click', function () {
console.log(this, 'this')
for (var j = 0; j < liS.length; j++) {
liS[j].className = ''
}
this.className = 'active'
})
}
</script>
</body>
</html>
07-28
2629
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-17
1657
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-05
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交