javascript - 如何使用 JS/React 在点击时复制链接 ID?

标签 javascript reactjs events

我有一个链接标记,如下所示:

<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/

相关文章:

javascript - Node.js 异步函数

javascript - 创建 OpenLayer 圈子时出现问题

javascript - 使用 focusMode 约束获取所需的媒体设备

javascript - ReactJS : onClick in sub-component does not trigger

events - 如何在 Fish shell 中设置退出时运行的函数?

c# - 将被点击的标签传递给它的点击方法。 C#

javascript - jQuery/Javascript : variable NOT updating after GET call

reactjs - 我在以下 react-redux 代码中遇到初始化错误

javascript - 错误: "domain option is required" in Auth0 create-react-app

Jquery点击事件传播