【问题标题】:copy to clipboard in JavaScript from row data从行数据复制到 JavaScript 中的剪贴板
【发布时间】:2021-04-01 09:41:56
【问题描述】:

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。我在关注the course

【问题讨论】:

  • 在该课程中,copyText 是一个元素 (document.getElementById("myInput")),而不是您要复制的文本
  • @brombeer 哦!是的……
  • @brombeer 我不知道该怎么做...你能帮忙吗?

标签: javascript html copy


【解决方案1】:

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);
}

【讨论】:

  • dummy_id 是什么?
  • 其实我们不需要。我编辑了我的答案。这里的关键是使用虚拟元素。
  • 既然可以使用navigator.clipboard.writeText()函数,为什么还要创建一个新元素?
  • @Prime 您之前的代码可以正常工作,但是新代码不能...为什么?
  • @McconnellMelany,它应该可以工作。你会再试一次吗?
【解决方案2】:

您的代码看起来像是在尝试复制一个数字,但是 w3 教程中的 copyPaste() 函数是用一个元素调用的。如果您想复制文本,navigator.clipboard.writeText() (MDN link) 是您的朋友。这就是你使用它的方式:

function copyPaste(number) {
  navigator.clipboard.writeText(number)
  alert(`The Number ${number} was copied.`)
}

编辑:代码不能在 JS 控制台中运行,因为页面需要处于焦点位置。如果你在网页上实现它,它应该可以工作。

【讨论】:

  • 哦!这是更漂亮的答案.. :) ;.. 我可以运行不带冒号的JS代码吗..?听说JS有更新了。。所以,我想知道原因,你没写。。。。?\
  • 在我之前的评论中,我说这个答案很漂亮,因为你刚刚在两行中完成了整个代码。但是,当我在我的代码中运行它时,我注意到我收到了警报消息,但无法复制......
  • 是的,分号在 JS 中是可选的。顺便说一句,如果它对您有帮助,您可以将我的答案标记为已接受:)
  • 哦,是的,如果你从控制台运行它,它不能复制它,因为窗口没有聚焦(页面本身需要聚焦,或者不允许修改剪贴板)。尝试在页面上实现它,它应该可以工作。
  • 不!我没有从控制台运行它。我只是改变了我的功能......
猜你喜欢
  • 2015-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 2017-03-02
相关资源
最近更新 更多