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

如何基于现有jQuery代码实现点击按钮复制文件链接到剪贴板

功能实现步骤

1. 新增复制功能全局函数

直接在你的JS代码中加入如下函数,即可处理点击后的复制逻辑:

function copyURI(e) {
  // 阻止a标签默认跳转行为
  e.preventDefault();
  // 获取当前点击元素对应的文件链接
  const fileUrl = e.currentTarget.getAttribute('href');
  // 调用浏览器剪贴板API写入内容
  navigator.clipboard.writeText(fileUrl).then(() => {
    // 复制成功提示,可替换为你自己项目的toast等提示样式
    alert('文件链接已复制到剪贴板');
  }).catch(err => {
    console.error('复制失败:', err);
    alert('复制失败,请手动复制链接');
  });
}

2. 原有jQuery代码优化(可选,建议修改)

原有代码存在几个小问题,调整后运行更稳定:

$('#select').on('change',function(){
  var criteria = $('#criteria :selected').val();
  $.ajax({
    type: 'POST',
    // 修正原data写法,补充id的取值逻辑,可根据你的实际需求调整
    data: {id: criteria},
    dataType: 'json',
    success: function(result) {
      var html = '';
      $.each(result, function (key, items) {
        html += '<tr>'; // 补上原代码缺失的行开头标签
        html += '<td>'+ items.id +'</td>';
        // 给属性值加引号,避免路径含特殊符号时出错
        html += '<td><a href="'+ criteria.naac_document +'"><i class="fa fa-download" title="下载" style="font-size:20px;color:red"></i></a></td>';
        // 修正复制按钮的title,原代码误写为Download
        html += '<td><a href="'+ criteria.naac_document +'" onclick="copyURI(event)"><i class="fa fa-copy" title="复制链接" style="font-size:20px;color:red"></i></a></td>';
        html += '</tr>';
      });
      $('.tbody').html(html);
    }
  });
});

低版本浏览器兼容方案

如果需要兼容不支持navigator.clipboardAPI的旧浏览器,可以把copyURI函数替换为如下实现:

function copyURI(e) {
  e.preventDefault();
  const fileUrl = e.currentTarget.getAttribute('href');
  // 创建临时文本域实现复制
  const tempInput = document.createElement('textarea');
  tempInput.value = fileUrl;
  document.body.appendChild(tempInput);
  tempInput.select();
  document.execCommand('copy');
  document.body.removeChild(tempInput);
  alert('文件链接已复制到剪贴板');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 12:15:01