我想知道上师是否可以帮助我解决这个问题。我有一张桌子,每一行都有一个按钮。按下复制按钮后,它应该复制该行单元格2中的语言。我能够收到警报,但是我需要将其复制到剪贴板,以便用户可以将其粘贴到另一个应用程序。此外,此方法适用于Chrome浏览器,但不适用于IE11。有两种方法都适用吗?非常感谢!
<table id="somerow">
<tr>
<th>CustomerNr</th>
<th>Name</th>
<th>Contact</th>
</tr>
<tr >
<td>1</td>
<td>Cigarettes Inc</td>
<td>Rambo</td>
<td><button class="otherButton" >Copy</button></td>
</tr>
<tr >
<td >22</td>
<td>Razor</td>
<td>David</td>
<td><button class="otherButton">Copy</button></td>
</tr>
<tr>
<td>3</td>
<td>H&M</td>
<td>Samuel Adams</td>
<td><button class="otherButton" >Copy</button></td>
</tr>
</table>
var a = document.getElementsByClassName('otherButton');
for (var i = 0; i<a.length;i++) {
a[i].addEventListener('click',function(){
var b = this.parentNode.parentNode.cells[1].textContent;
alert(b);
});
}
查看此copy-output-of-a-javascript-variable-to-the-clipboard,但要注意execCommand已过时。如果您的项目允许外部依赖,则可以使用clipboardjs
var a = document.getElementsByClassName('otherButton');
for (var i = 0; i < a.length; i++) {
a[i].addEventListener('click', function() {
var b = this.parentNode.parentNode.cells[1].textContent;
copyToClipboard(b);
alert(b);
});
}
function copyToClipboard(text) {
var dummy = document.createElement("text");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
<table id="somerow">
<tr>
<th>CustomerNr</th>
<th>Name</th>
<th>Contact</th>
</tr>
<tr>
<td>1</td>
<td>Cigarettes Inc</td>
<td>Rambo</td>
<td><button class="otherButton">Copy</button></td>
</tr>
<tr>
<td>22</td>
<td>Razor</td>
<td>David</td>
<td><button class="otherButton">Copy</button></td>
</tr>
<tr>
<td>3</td>
<td>H&M</td>
<td>Samuel Adams</td>
<td><button class="otherButton">Copy</button></td>
</tr>
</table>