How to create copy alerts in JavaScript?

荒凉一梦 提交于 2021-02-04 08:28:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!