I am trying to figure out why the copy to clipboard isn't working when I load a table from Javascript. If I don't load the table from a js file and put the table right in the HTML page, it works. Can somebody explain why it doesn't work and how to fix? Thanks!
HTML Page
<!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
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; 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);
});
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.