简体   繁体   English

Javascript 的复制到剪贴板问题

[英]Copy To Clipboard issue with Javascript

I am trying to figure out why the copy to clipboard isn't working when I load a table from Javascript.我试图弄清楚为什么当我从 Javascript 加载表格时复制到剪贴板不起作用。 If I don't load the table from a js file and put the table right in the HTML page, it works.如果我不从 js 文件加载表并将表放在 HTML 页面中,它可以工作。 Can somebody explain why it doesn't work and how to fix?有人可以解释为什么它不起作用以及如何解决吗? Thanks!谢谢!

HTML Page HTML 页

<!DOCTYPE html>
<!-- saved from url=(0014)about:internet -->
<html lang="en">
<html>
<head>
<title>Central</title>

<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="container">
    
<div id="Table">

</div>
        
</div>

</body>

<script type="text/javascript" src="Copy.js"></script>

<script>
var a = document.getElementsByClassName('CopyButton');

for (var i = 0; i < a.length; i++) {
  a[i].addEventListener('click', function() {
    var b = this.parentNode.parentNode.cells[2].textContent;
    //alert(b);
    copyToClipboard(b);
    
  });
}

function copyToClipboard(text) {
  var dummy = document.createElement("textarea");
  document.body.appendChild(dummy);
  dummy.value = text;
  dummy.select();
  document.execCommand("copy");
  document.body.removeChild(dummy);
}

window.onload = function() {
    
GetCopy();
   }
</script>
</html>

.js .js

function GetCopy() {
var data = '<table id="myTable"> \
<tr class="header"> \
<th>Title</th> \
<th></th> \
<th>Verbiage</th> \
</tr> \
<tr><td>Row 1</td> \
<td><input type="button" class="CopyButton" value="Copy" onclick="" /></td> \
<td>Copy Me 1</td> \
</tr> \
<tr><td>Row 2</td> \
<td><input type="button" class="CopyButton" value="Copy" onclick="" /></td> \
<td>Copy Me 2</td> \
</tr> \
</table>'
document.getElementById('Table').innerHTML =data; }

You need to attach the event listeners after the new HTML is added;添加新的 HTML 后,您需要附加事件侦听器; you are currently looking for the elements before you add them.您当前正在寻找元素,然后再添加它们。

window.onload = function() {
    GetCopy();
    var a = document.getElementsByClassName('CopyButton');
    
    for (var i = 0; i < a.length; i++) {
      a[i].addEventListener('click', function() {
        var b = this.parentNode.parentNode.cells[2].textContent;
        //alert(b);
        copyToClipboard(b);
        
      });
    }
}

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

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