异步获取的ISBN数据无法通过clipboard.js复制到剪贴板问题求助
问题排查与解决方案
原有代码的错误点
- 函数声明语法错误:
async function books_data{缺少括号,正确写法为async function books_data() - 变量引用错误:代码中出现的
val["JobID"]无定义,你实际需要赋值到隐藏input的是data["isbn"] - 缺少数组遍历逻辑:
/books接口返回的是多本书籍的数组,原有代码没有遍历逻辑,只能生成一行数据 - 多数据ID冲突:所有行的复制按钮都指向同一个ID为
foo的隐藏input,生成多行时最后一行的ISBN会覆盖之前所有行的赋值,点击任意行都会复制最后一行的ISBN - 未初始化clipboard.js实例:引入了clipboard.js但没有执行初始化代码,插件不会自动生效
- 隐藏元素兼容问题:部分浏览器下
display: none的元素无法被clipboard.js正确读取,会导致取值失败
推荐解决方案(原生Clipboard API实现,无第三方依赖)
该方案基于浏览器原生标准API开发,避开了已废弃的execCommand接口,不需要额外引入clipboard.js,也不需要设置隐藏input元素,兼容性覆盖95%以上的主流浏览器。
<script> async function books_data() { const response = await fetch('/books'); const dataList = await response.json(); const table = document.getElementById("myTable"); // 遍历所有书籍生成表格行 dataList.forEach(data => { const row = table.insertRow(); const cell1 = row.insertCell(0); const cell2 = row.insertCell(1); const cell3 = row.insertCell(2); const cell4 = row.insertCell(3); cell1.innerText = data.isbn; cell2.innerText = data.name; cell3.innerText = data.year; // 生成复制按钮并绑定事件 const copyBtn = document.createElement('button'); copyBtn.className = 'btn'; copyBtn.innerText = 'Copy to clipboard'; copyBtn.addEventListener('click', async () => { try { await navigator.clipboard.writeText(data.isbn); // 可选:添加复制成功状态提示 copyBtn.innerText = 'Copied!'; setTimeout(() => copyBtn.innerText = 'Copy to clipboard', 2000); } catch (err) { console.error('复制失败:', err); } }); cell4.appendChild(copyBtn); }) } </script> <table id="myTable"> <thead> <tr> <th>isbn</th> <th>name of book</th> <th>published year</th> <th>操作</th> </tr> </thead> <tbody></tbody> </table>
内容的提问来源于stack exchange,提问作者RyomenSukuna
相关产品推荐
相关产品推荐

