JS调用getElementById获取input元素返回null 无法复制值到剪贴板
问题原因
- 服务端模板变量
properties.anchor_name仅在HTML渲染阶段可被解析,直接写在客户端JS代码中不会被替换为实际的ID值,导致getElementById接收的参数无效,最终返回null - 即便成功获取DOM元素后,直接传入DOM对象到
writeText方法也无法得到输入框的实际内容,需要读取元素的value属性
修复方案
修改两处代码即可:
1. 调整HTML的按钮点击事件,将动态ID直接作为参数传入方法
<input type="text" value=${model.anchor_url} id=${properties.anchor_name}> <button class="c-button" onclick="myFunction('${properties.anchor_name}')"> <span class="c-button__label">Copy</span> </button> <div data-sly-test="${model.anchor_url}"> <p>URL from Model :</p> <pre>${model.anchor_url}</pre> </div>
2. 调整JS方法,接收ID参数并读取输入框值
function myFunction(inputId) { // 接收服务端直接传入的ID值,查找对应元素 const field = document.getElementById(inputId); if(!field) { alert("未找到对应输入框元素"); return; } // 读取输入框的value属性获取实际内容 const copyContent = field.value; // clipboard API是异步操作,添加回调处理成功/失败逻辑 navigator.clipboard.writeText(copyContent) .then(() => { alert("Copied the text to clipboard: " + copyContent); }) .catch(err => { alert("复制失败,请检查站点是否为HTTPS/localhost环境:" + err); }); }
额外注意
navigator.clipboard API仅支持在HTTPS协议或者localhost本地调试环境下使用,HTTP站点调用会抛出权限错误。
内容的提问来源于stack exchange,提问作者Anuska
相关产品推荐
相关产品推荐

