Click to add an object to the array and determine whether duplicate values have been included

Requirement: Now there are a bunch of lists. When I click each item in the list, I want to add this item to an array, and the added data cannot be added

renderings

 

 accomplish:

<!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>

Guess you like

Origin blog.csdn.net/qq_17211063/article/details/131439097