简体   繁体   English

Javascript剪贴板复制功能在点击锚标签时不起作用

[英]Javascript clipboard copy function not working onclick of anchor tag onclick

I want to copy a text into clipboard but for some reasons its not working nor it is throwing any errors .我想copy文本copyclipboard但由于某些原因它不起作用,也没有抛出任何errors

Below is my code.下面是我的代码。

function copy(obj)
{
     var $body = document.getElementsByTagName('body')[0];
      var $tempInput = document.createElement('INPUT');
      $body.appendChild($tempInput);
      $tempInput.setAttribute('value',  '1234')
      $tempInput.select();
      document.execCommand('copy');
      $body.removeChild($tempInput);
}   

I want to copy this text on click of anchor tag having href which is causing the issue it seems.我想在单击具有 href 的锚标记时复制此文本,这似乎导致了问题。 Any leads much appreciated.任何线索都非常感谢。

添加点击事件

onclick="copy(obj)"

obj is not using in your function copy obj未在您的函数copy

 function copyToClipboard() { location.href='#popup1'; var $body = document.getElementsByTagName('body')[0]; var $tempInput = document.createElement('INPUT'); $body.appendChild($tempInput); $tempInput.setAttribute('value', '1234') $tempInput.select(); document.execCommand('copy'); $body.removeChild($tempInput); alert("Text Copied"); }
 <a class="coup-copybutton" href="#" onclick="copyToClipboard()">Copy</a>

Your function works perfectly fine, I suspect your issue is with actually calling the function on button click.您的功能运行良好,我怀疑您的问题是在单击按钮时实际调用该功能。

Below is the exact same code you have, except I removed the obj parameter since it is never used.下面是您拥有的完全相同的代码,除了我删除了obj参数,因为它从未使用过。 I also created a button which calls the function when clicked.我还创建了一个按钮,单击时调用该函数。

 function copy() { var $body = document.getElementsByTagName('body')[0]; var $tempInput = document.createElement('INPUT'); $body.appendChild($tempInput); $tempInput.setAttribute('value', '1234') $tempInput.select(); document.execCommand('copy'); $body.removeChild($tempInput); } document.getElementById("copy_btn").onclick = copy;
 <button id="copy_btn">Copy</button> <input type="text" placeholder="Paste here..."/>

This works for me这对我有用

export const copyText = (text) => {
  const input = document.createElement('input');
  input.setAttribute('value', text);
  document.body.appendChild(input);
  input.select();
  const result = document.execCommand('copy');
  document.body.removeChild(input);
  return result;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM