嗨,如果你想复制动态表上的文本,你需要先 Select 元素.由于您不确定class/id是什么,所以只需 Select html元素即可
假设我有这个表,我想 Select td中的所有内部文本
<table >
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>
你可以在javascript上做的就是
让内容=文档.querySelectorAll('table tr td');//所有td都将被选中并添加到 node 列表中
之后,您需要将 node 列表转换为array.
让contentArr=Array.from(content)//可以使用array.从…起
然后循环浏览所有元素, for each 元素添加一个事件侦听器(单击),然后获取innerText并将其复制到剪贴板.你可以在这里查Hope it helps
contentArr.forEach((element) => {
element.addEventListener("click", (e) => {
let copyText = e.target.innerText
navigator.clipboard.writeText(copyText);
});
});
编辑:我在其中一条 comments 中看到,这就是你检测点击的方式
如果是这样的话,onclick函数是否会自动添加到您想要 Select 的div上?如果是
你能做的就是
<div onclick="copyAddress(this)">
在函数中添加此关键字
现在你可以在javascript上做的是
function copyAddress(e) {
navigator.clipboard.writeText(e.innerText); // the e is the current element and just get the innerText and copy it to clipboard.
}
编辑:
如果这是你的格式
<div onclick="copyAddress(this)"><textarea>text to copy</textarea></div>
function copyAddress(e) {
const copyText = e.firstChild;
copyText.select();
copyText.setSelectionRange(0, 99999);
navigator.clipboard.writeText(copyText.value);
}