首页 > 解决方案 > 从行数据复制到 JavaScript 中的剪贴板

问题描述

function copyPaste(number) {
        /* Get the text field */
      var copyText = number;

      /* Select the text field */
      copyText.select();
      copyText.setSelectionRange(0, 99999); /* For mobile devices */

      /* Copy the text inside the text field */
      document.execCommand("copy");

      /* Alert the copied text */
      alert("Copied the text: " + copyText);
    }
<th><p id="phone" onclick="copyPaste(<?php echo $row['phone'];?>)"><?php echo $row['phone']; ?></p></th>

我在没有<p>标签的情况下工作。它也不起作用..错误:Uncaught TypeError: copyText.select is not a function at copyPaste ((index):109) at HTMLParagraphElement.onclick来自控制台。我正在关注课程

标签: javascripthtmlcopy

解决方案


select()是一种方法HTMLInputElement。目前,copyText是一个字符串。要使用copy命令,您需要在 Html 中创建虚拟输入。

function copyPaste(number) {
  var dummy = document.createElement("input");

  // Add it to the document
  document.body.appendChild(dummy);

  // Set value of input 
  dummy.value = number;

  /* Select the text field */
  dummy.select();
  dummy.setSelectionRange(0, 99999); /* For mobile devices */

  /* Copy the text inside the text field */
  document.execCommand("copy");

  // Remove it as its not needed anymore
  document.body.removeChild(dummy);

  /* Alert the copied text */
  alert("Copied the text: " + number);
}

推荐阅读