问题
I am working on a quote website project.
Note the <span class="status-copy-alert">Copied</span>
in part 1.
In the css the visibility of span is hidden. Can anyone modify part 2 so when the the copy button next to the span in part 1 with onclick function is clicked, the span should be visible.
Part 1
contents.innerHTML = paged.map(record => `<div class='latestatus'>
<p class='copytxt'>${record.status}</p>
<div>
<button class="copystatus btn" onclick='copyTextToClipboard("${record.status}")' >Copy</button>
<span class="status-copy-alert">Copied!</span>
</div>
</div>`).join('');
resultEl.append(contents);
Part 2
function copyTextToClipboard(text) {
const copyText = document.createElement('textarea');
copyText.style.position="absolute";
copyText.value = text;
document.body.appendChild(copyText);
copyText.select();
document.execCommand('copy');
document.body.removeChild(copyText);
}
回答1:
I would delegate
contents.innerHTML = paged.map(record => `<div class='latestatus'>
<p class='copytxt'>${record.status}</p>
<div>
<button class="copystatus btn">Copy</button>
<span class="status-copy-alert">Copied!</span>
</div>
</div>`).join('');
resultEl.append(contents);
resultEl.addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.classList.contains("copystatus")) {
copyTextToClipboard(tgt.closest(".latestatus")
.querySelector("p.copytxt").textContent)
tgt.closest("div").querySelector(".status-copy-alert").style.display = "inline";
}
});
来源:https://stackoverflow.com/questions/65843770/how-to-create-copy-alerts-in-javascript