我有一个链接标记,如下所示:
<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>
关于javascript - 如何使用 JS/React 在点击时复制链接 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60365358/