简体   繁体   English

如何使用 HTML/JS 中的按钮将来自 Anchor 的 href 链接复制到剪贴板?

[英]How to use a button in HTML/JS to copy to the Clipboard the href link from an Anchor?

I have an html file with a table collecting in every row several web links (url), and in the same table I would like to have a button for every row, that copies to the Clipboard the link of that row (embedded as 'href' in an anchor tag), giving to the user a feedback popup.我有一个 html 文件,其中的表格在每一行中收集了几个 web 链接(url),并且在同一个表格中,我希望每一行都有一个按钮,它将该行的链接复制到剪贴板(嵌入为'href ' 在锚标记中),给用户一个反馈弹出窗口。

I've tried in several ways but it seems that most of the available examples show how to achieve that just for input fields, moreover with hard-coded functions that do not receive as a parameter the reference id for the text to be copied.我已经尝试了几种方法,但似乎大多数可用示例都显示了如何仅针对输入字段实现这一点,此外,硬编码函数不接收要复制的文本的参考 ID 作为参数。

Any ideas?有任何想法吗?

-UPDATE- I solved my problem thanks to the suggestion of Maassander. -更新-由于 Maassander 的建议,我解决了我的问题。 Unfortunately the suggested thread was not specific enough for my issue: How do I copy to the clipboard in JavaScript?不幸的是,建议的线程对我的问题不够具体: 如何在 JavaScript 中复制到剪贴板?

The most basic version of this would look something like this I guess:我猜这个最基本的版本看起来像这样:

 var rows = document.getElementsByClassName('table-row'); for (var i = 0; i < rows.length; i++){ var button = rows[i].querySelector('button'); button.addEventListener('click', function(e){ var link = e.target.closest('tr').querySelector('a'); var tempText = document.createElement('textarea'); tempText.value = link.href; document.body.appendChild(tempText); tempText.select(); document.execCommand('copy'); document.body.removeChild(tempText); }); }
 <table> <tr class="table-row"> <td><a href="https://www.google.com">Google</a></td> <td><button type="button">Copy</button></td> </tr> <tr class="table-row"> <td><a href="https://stackoverflow.com/">Stack Overflow</a></td> <td><button type="button">Copy</button></td> </tr> </table>

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

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