简单思路:点击的时候,判断这个点击的id是否 等于选中的id数组(selectedArr)里面的id,那再点击就是取消选中,找到这个选中的id位置,删掉它
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>666Hello React!</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<style>
.red {
color: red;
}
</style>
</head>
<body>
<a class="js-click" id="1">企业软件(ERP)</a><br><br><br>
<a class="js-click" id="2">办公自动化OA系统</a><br><br><br>
<a class="js-click" id="3">客户关系管理(CRM)</a><br><br><br>
<a class="js-click" id="4">CMS系统开发</a><br><br><br>
</body>
<script>
$(document).ready(function () {
// 存储选中的id
let selectedArr = []
$("a").click(function () {
let id = $(this).attr('id')
let hasId = ''
selectedArr.forEach(function (item, key) {
// 判断点击的id 存在选中的id里面,再点击就是取消选中
if (item == id) {
hasId = (key + 1)
selectedArr.splice(key, 1)
}
})
if (!hasId) {
selectedArr.push(id)
}
$('.js-click').removeClass('red')
$('.js-click').each(function () {
if (selectedArr.indexOf($(this).attr('id')) > -1) {
$(this).addClass('red')
}
})
})
})
</script>
</html>