You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用原生JavaScript从a标签的href复制链接到剪贴板

问题:复制链接的href属性值到剪贴板

页面中有带生成URL的<a>标签,当标签显示静态文本(例如“Klicka för att ansluta till mötet”)隐藏长URL时,点击按钮只能复制静态文本,需要改为复制<a>标签的href属性中的URL,无论URL是动态生成还是固定值。

现有代码问题

原脚本中使用$(element).text()获取的是<a>标签的显示文本,而非href属性值,因此无法复制目标URL。

修改方案

只需将脚本中获取文本的部分,改为获取<a>标签的href属性值即可:

修改后的脚本

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  // 替换text()为attr('href'),获取a标签的href属性值
  $temp.val($(element).attr('href')).select();
  document.execCommand("copy");
  $temp.remove();
}

完整示例代码

场景1:动态生成URL的情况

<button class="btn" id="copy_button" onclick="copyToClipboard('#url')">Copy the link</button>

<code>
  <a id="url" class="url" href='' target="UrlGenerator"></a>
</code>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).attr('href')).select();
  document.execCommand("copy");
  $temp.remove();
}

// 模拟动态生成URL
$(function() {
  $('#url').attr('href', 'https://dynamic-generated-url.example.com');
});
</script>

场景2:固定URL的情况

<button class="btn" id="copy_button" onclick="copyToClipboard('#url')">Copy the link</button>

<a id="url" class="url" href="https://example.com">Klicka för att ansluta till mötet</a>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).attr('href')).select();
  document.execCommand("copy");
  $temp.remove();
}
</script>

原理说明

  • $(element).attr('href')会直接获取目标<a>标签的href属性值,不管该值是静态写死还是后续通过JS动态生成的。
  • 其余逻辑保持不变:创建临时输入框写入URL,选中后执行复制命令,最后移除临时输入框。

内容的提问来源于stack exchange,提问作者PelleH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 03:03:28