簡體   English   中英

Javascript剪貼板復制功能在點擊錨標簽時不起作用

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

我想copy文本copyclipboard但由於某些原因它不起作用,也沒有拋出任何errors

下面是我的代碼。

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

我想在單擊具有 href 的錨標記時復制此文本,這似乎導致了問題。 任何線索都非常感謝。

添加點擊事件

onclick="copy(obj)"

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>

您的功能運行良好,我懷疑您的問題是在單擊按鈕時實際調用該功能。

下面是您擁有的完全相同的代碼,除了我刪除了obj參數,因為它從未使用過。 我還創建了一個按鈕,單擊時調用該函數。

 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..."/>

這對我有用

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