前端利用weakMap实现添加课程
代码实现(复制可直接用)
<!DOCTYPE html>
<html>
<head>
<title>添加课程</title>
</head>
<style>
*{margin: 0;padding: 0;}
body{
display: flex;
justify-content: center;
/* align-items: center; */
}
div{
width: 400px;
height: 300px;
border: 1px solid black;
}
li{
list-style: none;
}
h2{
text-align: center;
}
.d1 ul li{
margin: auto;
width: 250px;
height: 50px;
font-size: 20px;
background-color: cadetblue;
border-radius: 5px;
margin-top: 10px;
line-height: 50px;
padding-left: 20px;
}
.xuanze_u1 a{
margin-top: 10px;
margin-right: 10px;
background-color:green;
text-decoration:none;
color: black;
width: 25px;
height: 25px;
float: right;
border: 1px solid black;
text-align: center;
line-height: 25px;
}
span{
background-color: cadetblue;
height: 20px;
margin-left: 10px;
border-radius: 5px;
}
</style>
<body>
<div class="d1">
<h2>选择课程</h2>
<ul class="xuanze_u1">
<li><span> js特效</span><a >+</a></li>
<li><span>JAVA</span><a>+</a></li>
<li><span>c语言</span><a >+</a></li>
<li><span>Lyh</span><a >+</a></li>
</ul>
</div>
<div id="d2">
<h2></h2>
<p id="lists">
</p>
</div>
<script>
class lesson{
constructor(){
this.lis=document.querySelectorAll('ul>li');
this.lists=document.getElementById('lists');
this.map=new WeakMap(); // new Map() new WeakMap() 也可以
}
run(){
this.lis.forEach((li,i)=> {
li.querySelector('a').addEventListener('click',event=> {
let a=event.target;
let ste=li.getAttribute('selece'); //返回只是属性值;
// console.log(i);
// console.log(ste);
if (ste) {
li.removeAttribute('selece');
this.map.delete(li);
a.style.backgroundColor="green";
a.innerHTML="+";
} else {
li.setAttribute('selece',true); //将selece 的属性值改为true 以备if使用
this.map.set(li);
a.style.backgroundColor="red";
a.innerHTML="-";
}
this.runden();
})
})
}
count(){
return [...this.lis].reduce((count,cut)=>{ //计数 判断数组中存入的还有几个
return (count+=this.map.has(cut)?1:0);
},0)
}
maps(){
return [...this.lis].filter(li=>{
return this.map.has(li); //过滤出 map中含有的 li; 再进行map循环 获取span中的文本用字符串联接 赋值给p标签的文本;
}).map(li=>{
return `<span>${li.querySelector("span").innerHTML}</span>`
}).join('');
}
runden(){
let h2=document.querySelector("[id='d2']>h2");
this.lists.innerHTML= this.maps();
h2.innerHTML=`已选择${this.count()}门课程`;
}
}
let li=new lesson();
li.run();
li.runden();
</script>
</body>
</html>
- 点击“+”右边会添加到已选课程
- 点击完加号后会直接变成“-”减去已选课程
视频:
实现选课功能