1 回答
TA贡献1851条经验 获得超5个赞
const tagContainerNodes = document.querySelectorAll(".tag-container");
tagContainerNodes.forEach((tagContainerNode) => {
const input = tagContainerNode.querySelector("input");
input.addEventListener("keyup", e => {
if (e.key === "Enter") {
createTag(e.target.value, tagContainerNode, input);
e.target.value = "";
}
});
});
function createTag(tagName, parent, before) {
var div = document.createElement("div");
div.setAttribute("class", "tag");
var span = document.createElement("span");
span.innerHTML = tagName;
div.appendChild(span);
parent.insertBefore(div, before)
}
function clicked() {
const allTagText = [];
tagContainerNodes.forEach((tagContainerNode) => {
const tagNodes = tagContainerNode.querySelectorAll(".tag");
tagNodes.forEach((tagNode) => {
allTagText.push(tagNode.textContent);
});
});
console.log(allTagText);
}
.tag-container {
border: 2px solid #ccc;
padding: 10px;
border-radius: 5px;
display: flex;
}
.tag-container .tag {
padding: 5px;
border: 1px solid #ccc;
margin: 5px;
border-radius: 3px;
background: #f2f2f2;
box-shadow: 0 0 4px rgba(0, 0, 0, 0.2), inset 0 1px 1px #fff;
}
.tag-container input {
font-size: 16px;
padding: 5px;
outline: none;
border: 0;
}
<div class="tag-container">
<input id="input_search" />
</div>
<button type="button" onclick="clicked()">Button</button>
<div class="tag-container">
<input id="input_search" />
</div>
<button type="button" onclick="clicked()">Button</button>
<div class="tag-container">
<input id="input_search" />
</div>
<button type="button" onclick="clicked()">Button</button>
添加回答
举报