我有:

HTML代码:

<div class="server-ip clearfix">
<p>
  <i class="ion-ios-world"></i>
  <span id="serv-1">play.minesuperior.com</span>
</p>
<a class="copy-action" href="#!" onclick="copyText('serv-1')">
    <span class="copy-text">
      <i class="ion-scissors"></i>
      Copy
    </span>
</a>
</div>


JS功能:

function copyText(textToCopy) {
  var copyText = document.getElementById(textToCopy).textContent;
  console.log(copyText);

  copyText.select();
  document.execCommand("Copy");

  alert("Copied the text: " + copyText);
}


我得到错误:

Uncaught TypeError: copyText.select is not a function

为什么?在函数中,我传递参数:play.minesuperior.com
我在console.log中尝试了param函数,然后得到了文本。

最佳答案

尝试下面的代码片段,



function CopyToClipboard(containerid) {

    var range = document.createRange();
     range.selectNode(document.getElementById(containerid));
     window.getSelection().addRange(range);
     document.execCommand("copy");
     alert("text copied") ;
}

<div class="server-ip clearfix">
                <p>
                  <i class="ion-ios-world"></i>
                  <span id="serv-1">play.minesuperior.com</span>
                </p>
                <a class="copy-action" href="#!" onclick="CopyToClipboard('serv-1')">
                    <span class="copy-text">
                      <i class="ion-scissors"></i>
                      Copy
                    </span>
                </a>
  </div>

07-24 09:50
查看更多