如何为许多按钮制作这个 copybutton Javascript?

问题描述

谁能帮忙破解这个Javascript?

const copyButton = document.querySelector('.copyButton');
const copyalert = document.querySelector('.copyalert');

copyButton.addEventListener('click',copyClipboard);

function copyClipboard() {
  var copystatus= document.getElementById("randomstatus");
// for Internet Explorer

  if(document.body.createTextRange) {
    var range = document.body.createTextRange();
    range.movetoElementText(copystatus);
    range.select();
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
    copyalert.classList.add("show");
    setTimeout(function() {copyalert.classList.remove("show")},700);
  }
  else if(window.getSelection) {
// other browsers

    var selection = window.getSelection();
    var range = document.createrange();
    range.selectNodeContents(copystatus);
    selection.removeAllRanges();
    selection.addRange(range);
    document.execCommand("copy");
    window.getSelection().removeAllRanges();
    copyalert.classList.add("show");
    setTimeout(function() {copyalert.classList.remove("show")},700);
  }
}

此 javascript 用于复制 <p> 元素内的文本。 我的HTML代码

<p id="randomstatus">Strangers think I'm Quiet. My Friends think I'm outgoing. My best friends kNow that I'm Completely Insane</p>
    <button class="copyButton btn" id="copyButton"><i class="fas fa-clipboard"></i>  copy</button>
    <span class="copyalert">copied!</span>

这非常适合一个人,但我需要复制按钮在我的网页中放置更多次。但我一直卡在这里。请帮帮我。

解决方法

一种基本方法是为每个按钮添加一个 onclick 事件属性,用于调用 copyClipboard() 函数

<button class="copyButton btn" id="copyButton" onclick = 'copyClipboard()'><i class="fas fa-clipboard"></i>  Copy</button>
<button class="copyButton btn" id="copyButton1" onclick = 'copyClipboard()'><i class="fas fa-clipboard"></i>  Copy</button>

并将您的 JavaScript 脚本更改为此

function copyClipboard() {
    var copyalert = document.querySelector('.copyalert');
    var copystatus= document.getElementById("randomstatus");
    // for Internet Explorer

    if(document.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(copystatus);
        range.select();
        document.execCommand("Copy");
        window.getSelection().removeAllRanges();
        copyalert.classList.add("show");
        setTimeout(function() {copyalert.classList.remove("show")},700);
    }
    else if(window.getSelection) {
        // other browsers

        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(copystatus);
        selection.removeAllRanges();
        selection.addRange(range);
        document.execCommand("Copy");
        window.getSelection().removeAllRanges();
        copyalert.classList.add("show");
        setTimeout(function() {copyalert.classList.remove("show")},700);
    }
}