需求:现在有一堆列表,当我每次点击列表的每一项时,希望将此项添加到一个数组中,并且已添加的数据不能再添加
效果图
实现:
<!DOCTYPE html>
<html lang="zh">
<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta http-equiv="X-UA-Compatible" content="ie=edge" /><title>点击选择元素</title><style type="text/css">#warp{display:flex;justify-content:center;}span{margin:10px; width:150px;line-height:45px;background:#eee;text-align:center; display:block;cursor:pointer;font-size:14px;}</style>
</head>
<body><div id="warp"><span data-url="/art-cate">文章分类</span><span data-url="/art-list">文章列表</span><span data-url="/user-info">基本资料</span><span data-url="/user-avatar">更换头像</span><span data-url="/user-pwd">重置密码</span></div>
</body>
</html>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">$(function(){var arr = []$('span').click(function(){var this_obj = {title:$(this).text(),url:$(this).attr('data-url')}console.log('当前选择的:',this_obj)let indexTow = arr.findIndex((e) => {return e.url == this_obj.url;});if (indexTow < 0) {arr.push(this_obj);}console.log('新数组:',arr)});});
</script>