javascript - TypeError:text.select 不是函数
问题描述
我正在尝试使用 js 实现复制到剪贴板功能。
我有一张桌子:
<tbody>
<tr>
<td>1.</td>
<td id="kord">(35|154)</td>
<td id="gorj">15</td>
<td>3,6</td>
<td><button type="button" onclick="copyKord()">Kopiraj</button></td>
<td><button type="button" onclick="copyGorj()">Kopiraj</button></td>
<td><input type="number"></td>
</tr>
</tbody>
我的js函数:
function copyKord(){
var text = document.getElementById("kord").innerHTML;
console.log(text);
text.select();
document.execCommand("copy");
}
因此,当我按下按钮时,当我 console.log 显示文本的变量时,出现错误“TypeError:text.select 不是 copyKord 的函数”。我尝试使用插入 td 元素的 textarea ,但它仍然无法正常工作。
解决方案
您可以使用navigator.clipboard.writeText
来执行copy
操作。
function copyKord(){
var text = document.getElementById("kord").innerHTML;
navigator.clipboard.writeText(text);
}
function copyGorj() {
var text = document.getElementById("gorj").innerHTML;
navigator.clipboard.writeText(text);
}
<table>
<tbody>
<tr>
<td>1.</td>
<td id="kord">(35|154)</td>
<td id="gorj">15</td>
<td>3,6</td>
<td><button type="button" onclick="copyKord()">Kopiraj</button></td>
<td><button type="button" onclick="copyGorj()">Kopiraj</button></td>
<td><input type="number"></td>
</tr>
</tbody>
</table>
推荐阅读
- php - 如何在 php 中按值对数组进行切片或拼接?
- node.js - 当有一些节点实例时,如何正确处理 worker_threads 终止?(如 docker-swarm 或 Kubernetes 集群)
- perl - 为什么 Perl 的 Devel::Cover 认为有些分支和条件没有被覆盖?
- time - Youtrack 和 Jira 的“2d 4h 30m”时间段格式有名称吗?
- java - plantext模式下的Kafka,客户端需要在properties中设置哪些字段才能创建producer?(Java程序中)
- r - 使用 ggplot2 对两条直线之间的区域进行着色
- reactjs - 反应 + 烧瓶 ec2 部署
- c# - .NET EF 4.7.2 MVC Create 方法转换子表单提交
- python - 将多次运行的函数的输出组合到一个列表中
- tailwind-css - 如何使用 TailwindCSS 更改网格行的背景颜色