jq realizes the website - click on the label, add it to a box, click again to remove the label

Realize the effect:

insert image description here

Code logic:

First use the hasClass() method to determine whether the clicked label already exists in the box. If the label already exists in the box, use the removeClass() method to remove the label's 'active' class name, and use the filter() method to find the element in the box with the same text as the clicked label, and use the remove() method to remove it remove;

If the label does not exist in the box, add the 'active' class name of the label using the addClass() method and use $('

') to create a new
element, and use the text() method to set its text content as the clicked label text, and finally use the appendTo() method to append the newly created
Elements are added to the box.

Code:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="html/js/jquery.min.js"></script>  //引入juery库
		<style>
			.bidbox {
      
      
				border: 1px solid #000;
				width: 500px;
				margin-bottom: 30px;
			}

			.labelbox {
      
      
				background-color: beige;
				display: flex;
				align-items: center;
				justify-content: flex-start;
			}

			.labelbox div {
      
      
				margin-right: 10px;
				background: dodgerblue;
				padding: 5px;
				color: #fff;
			}

			.container {
      
      
				display: flex;
				align-items: center;
			}

			.container .tag {
      
      
				background: dodgerblue;
				color: #fff;
				margin-right: 10px;
				cursor: pointer;
			}
		</style>
	</head>
	<body>
		<div class="bidbox">
			<p>选中的标签:</p>
			<div class="labelbox">
				<!-- 这里是添加的标签 -->
			</div>
		</div>

		<p>点击以下标签进行选择:</p>
		<div class="container">
			<div class="tag">标签1</div>
			<div class="tag">标签2</div>
			<div class="tag">标签3</div>
			<div class="tag">标签4</div>
		</div>
	</body>
	<script>
		$(document).ready(function() {
      
      
			$('.tag').click(function() {
      
      
				var tag = $(this).text(); // 获取点击的标签的文本

				if ($(this).hasClass('active')) {
      
      
					// 如果标签已经存在于盒子中,则从盒子中移除该值
					$(this).removeClass('active');
					$('.labelbox').children().filter(function() {
      
      
						return $(this).text() === tag;
					}).remove();
				} else {
      
      
					// 如果标签不存在于盒子中,则将其添加到盒子中
					$(this).addClass('active');
					$('<div>').text(tag).appendTo('.labelbox');
				}
			});
		});
	</script>
</html>

Finish!

Guess you like

Origin blog.csdn.net/weixin_48596030/article/details/131738612