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

JavaScript复制到剪贴板功能仅复制首个表格单元格问题求解

问题核心原因

  1. 所有行的隐藏输入都使用了相同的id="Key",DOM规范要求id必须全局唯一,因此document.getElementById("Key")永远只会匹配到页面中第一个出现的对应元素
  2. 把<script>标签放在循环输出的<tr>内部,会导致页面重复定义多次myFunction,最终仅最后一次定义的函数生效
  3. 存在HTML结构错误:<div>直接放在<tr>和<td>之间不符合表格渲染规范,可能导致页面渲染异常

修复方案

方案1:最小改动兼容旧逻辑

首先修改循环输出的表格行代码:

<tr>
    <td class="ttd">&nbsp;</td>
    <td class="ttd"><?php echo htmlentities($f['ID']); ?> </td>
    <td class="ttd"><?php echo htmlentities($f['Invoice_number']); ?> </td>
    <td class="ttd"><?php echo htmlentities($f['Invoice_date']); ?> </td>
    <td class="ttd"><?php echo htmlentities($f['Month']); ?> </td>
    <td class="ttd"><?php echo htmlentities($f['Space_name']); ?> </td>
    <td class="ttd"><?php echo htmlentities($f['Company_name']); ?> </td>
    <td class="ttd"><?php echo htmlentities($f['Amount']); ?> </td>
    <td class="ttd">
        <div class="tooltip">
            <input type="text" style="display:none;" class="copy-key" value="hhhhhhh.php?token=<?php echo $current_token['token']; ?>">
            <button onclick="myFunction(this)" >Copy</button>
        </div>
    </td>
</tr>

然后把原来写在<tr>内部的JS代码删除,全局仅在页面</body>标签之前写一次即可:

// 注意补全send变量的定义,原代码未定义该变量会导致报错
let send = 0;
document.forms[0].addEventListener("submit", function(event){
    if ( send == 0 ) { event.preventDefault(); }
});

function myFunction(btn) {
    // 从当前点击的按钮定位到对应行的隐藏输入
    var hidden = btn.parentElement.querySelector('.copy-key');
    hidden.style.display = 'block';
    hidden.select();
    hidden.setSelectionRange(0, 99999);
    document.execCommand("copy");
    alert("Copied the text: " + hidden.value);
    hidden.style.display = 'none';
}

方案2:现代API优化(更简洁)

可以直接去掉隐藏输入元素,用HTML自定义属性存储要复制的内容,配合原生Clipboard API实现,代码更简洁:
按钮修改为:

<button onclick="myFunction(this)" data-copy="hhhhhhh.php?token=<?php echo $current_token['token']; ?>">Copy</button>

对应的JS逻辑:

let send = 0;
document.forms[0].addEventListener("submit", function(event){
    if ( send == 0 ) { event.preventDefault(); }
});

function myFunction(btn) {
    const copyContent = btn.dataset.copy;
    navigator.clipboard.writeText(copyContent).then(() => {
        alert("Copied the text: " + copyContent);
    }).catch(err => {
        alert("复制失败:" + err);
    });
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 17:27:03