<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
ul{
list-style: none;
width: 300px;
margin: 100px auto;
border: 1px solid #000;
}
.selected{
background: red;
}
</style>
</head>
<body>
<ul>
<li class="selected">我是第1个li</li>
<li>我是第2个li</li>
<li>我是第3个li</li>
<li>我是第4个li</li>
<li>我是第5个li</li>
</ul>
<script type="text/javascript">
/* let oItems = document.querySelectorAll("ul>li");
let currentItem=oItems[0];
for(let item of oItems)
{
item.οnclick=change;
}
function change()
{
currentItem.className="";//获取的是当前的上一次的为““
this.className="selected";//当前的为红色。
currentItem=this;//当前的赋值为上一次。
}*/
let oUl = document.querySelector("ul");
let oLi = document.querySelector(".selected");
oUl.onclick=function(event)
{
event=event||window.event;
oLi.className="";
let item=event.target;
item.className="selected";
oLi=item;
}
//无非三点:上一次的设为”“,当前的加上className,然后是把当前的赋值给上一次。
</script>
</body>
</html>