<!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>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
ul {
list-style: none;
border: 2px solid rgb(56, 54, 54);
width: 50%;
}
li {
position: relative;
border: 2px solid orangered;
margin: 10px;
width: 80%;
padding: 10px;
}
#container {
height: 212px;
margin: 10px;
}
#container ul,
#container div {
height: 100%;
float: left;
}
.content {
border: 2px solid rgb(56, 54, 54);
width: 50%;
margin-left: -1px;
}
#lists span{
background-color: rgb(7, 126, 52);
padding:0 10px;
border-radius: 5px;
margin-right: 10px;
}
a {
position: absolute;
right: 10px;
top:10px;
text-decoration: none;
background-color: green;
width: 32px;
text-align: center;
color: #fff;
line-height: 32px;
}
</style>
</head>
<body>
<div id='container'>
<ul>
<li><span>php</span><a href="javascript:;">+</a></li>
<li><span>js</span><a href="javascript:;">+</a></li>
<li><span>项目</span><a href="javascript:;">+</a></li>
</ul>
<div class="content">
<span id='count'>共选了0门课</span>
<p id='lists'>
</p>
</div>
</div>
<script>
class Lesson{
constructor(){
this.lis = document.querySelectorAll('ul>li')
this.countElem = document.getElementById('count')
this.listElem = document.getElementById('lists')
this.map = new WeakMap()
// console.log(this.lis);
// console.log(this.countElem);
// console.log(this.listElem);
}
run(){
this.lis.forEach(li => {
li.querySelector('a').onclick = (event) => {
// console.log(event.target.parentElement);
// console.log(this); //指向实例对象
const status = li.getAttribute('select')
const a = event.target
if(status){
//status 为true时,表示已选,
li.removeAttribute('select')
this.map.delete(li)
a.innerHTML = "+"
a.style.backgroundColor = 'green'
}else{
li.setAttribute('select',true)
this.map.set(li)
a.innerHTML = "-"
a.style.backgroundColor = 'red'
}
this.render()
}
})
}
count(){
// count是数量,li 是当前遍历到的元素
return [...this.lis].reduce((count,li) => {
return count += (this.map.has(li) ? 1 : 0)
},0) //count的初始值为0
}
list(){
return [...this.lis].filter(li =>{
return this.map.has(li)
})
.map(li => {
return `<span>${li.querySelector('span').innerHTML}</span>`
})
.join('')
}
render(){
this.countElem.innerHTML = `共选了${this.count()}门课`
this.listElem.innerHTML = this.list()
}
}
let l = new Lesson()
l.run()
</script>
</body>
</html>
选课
最新推荐文章于 2024-09-11 18:14:11 发布