[英]How can I copy a link id on a click using JS / React?
我有一个链接标签如下:
<a onClick={this.linkClicked} id='some_string'>
<svg className ='medd_link' xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24"> ... </svg>
</a>
当用户单击链接时,我希望将 id 'some_string' 复制到剪贴板。
我将如何实现这一点?
linkClicked = (event) => {
// const element = document.getElementById("myInput");
// we are using react so we will work with the virtual DOM not the actual DOM
// event.target maybe?
// element.select();
// element.setSelectionRange(0, 99999)
document.execCommand("copy");
// why does event.target point to the svg element?
alert("Copied the text: ");
}
更新
我注意到的第一个奇怪的事情是 event.target 指向<svg>
元素而不是我需要访问的<a>
元素。
onClick = (event, text) => { event.preventDefault(); input = document.createElement("input"); input.style="position:absolute;opacity:0"; input.value = text; document.body.append(input); input.select(); document.execCommand("copy"); input.remove(); alert("Copied the text: " + text); }
<a id='some_string' onclick="onClick(event, this.id)">click here</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.