js to add multiple tags with deletion
Here's an example of how to add multiple tags with deletion functionality:
HTML:
<div id="tag-container">
<div class="tag-item">Tag 1 <span class="delete-tag">×</span></div>
<div class="tag-item">Tag 2 <span class="delete-tag">×</span></div>
<div class="tag-item">Tag 3 <span class="delete-tag">×</span></div>
<input type="text" id="tag-input" placeholder="Add a tag">
</div>
CSS:
.tag-item {
display: inline-block;
background-color: #f1f1f1;
color: #333;
padding: 8px;
margin: 0 5px 5px 0;
border-radius: 5px;
}
.delete-tag {
cursor: pointer;
margin-left: 5px;
}
JS:
const tagContainer = document.getElementById('tag-container');
const tagInput = document.getElementById('tag-input');
tagInput.addEventListener('keydown', function(event) {
if (event.keyCode === 13) { // enter key
const tagText = tagInput.value.trim();
if (tagText !== '') {
const tagItem = document.createElement('div');
tagItem.classList.add('tag-item');
tagItem.textContent = tagText;
const deleteTag = document.createElement('span');
deleteTag.classList.add('delete-tag');
deleteTag.innerHTML = '×';
deleteTag.addEventListener('click', function() {
tagItem.remove();
});
tagItem.appendChild(deleteTag);
tagContainer.insertBefore(tagItem, tagInput);
tagInput.value = '';
}
}
});
This code listens for the enter key to be pressed while the tag input field is focused. When the enter key is pressed, it checks if the input field is not empty. If it's not empty, it creates a new tag item with the entered text and adds a delete button to it. The delete button has a click event listener that removes the tag item from the container when clicked. The new tag item is then added to the container before the input field, and the input field is cleared.
原文地址: https://www.cveoy.top/t/topic/B1z 著作权归作者所有。请勿转载和采集!