PHP动态生成多行内容后,复制到剪贴板按钮始终复制首行如何解决?
解决方案
问题根因
- 循环计数变量使用错误:你的遍历逻辑用
$x作为计数变量,但生成元素ID时用了未定义的$i,导致所有行的<p>标签ID完全重复,DOM规范里相同ID的元素只会返回第一个匹配项,因此每次点击都复制第一行内容 - 函数定义冗余:你把
copyTo函数放在了for循环内部,每次遍历都会重复定义同名函数,属于无效冗余代码
具体修改步骤
- 把公共JS函数移到循环外部,放在页面底部统一加载
- 用循环变量
$x生成每行唯一的ID,保证每个复制按钮对应唯一的内容元素
修改后的代码示例
公共JS代码(放在页面</body>标签前即可,不要放在循环内)
function copy(element_id) { var aux = document.createElement("div"); aux.setAttribute("contentEditable", true); aux.innerHTML = document.getElementById(element_id).innerHTML; aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)"); document.body.appendChild(aux); aux.focus(); document.execCommand("copy"); document.body.removeChild(aux); }
业务循环代码
$numresults=$info["count"]; echo"<div style='position: fixed; float: right; padding-left: 450px;'><a class=clear href=javascript:history.go(-1)>Search again</a></div>"; echo "<div><p>There are <b>$numresults</b> results for your search '<i><b>$SearchFor</i></b>'"; if ($numresults>0){ echo " these are:</p></div>"; echo "<div>"; for ($x=0; $x<$numresults; $x++) { $sam=$info[$x]['samaccountname'][0]; $disp=$info[$x]['displayname'][0]; $dir=$info[$x]['homedirectory'][0]; $fil=$info[$x]['homedirectory'] [0]; $displayout=substr($sam, 0, 4); echo "User Name : $sam"; echo "<br>Name : $disp"; echo "<br>Home Drive : <a class=clear href=$dir>$dir</a><br>"; // 用循环变量$x生成唯一ID ?> <p id="demo<?php echo $x; ?>"> <?php echo $dir ?> </p> <button onclick="copy('demo<?php echo $x; ?>')">Copy Keeping Format</button> <br><br> <?php } echo "</div>"; }
优化方案(可选,无需额外p标签存储内容)
直接把要复制的内容作为参数传给JS函数,从根源避免ID重复问题:
// 优化后的复制函数 function copyDirect(content) { var aux = document.createElement("div"); aux.setAttribute("contentEditable", true); aux.innerHTML = content; aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)"); document.body.appendChild(aux); aux.focus(); document.execCommand("copy"); document.body.removeChild(aux); }
对应按钮代码简化为:
<button onclick="copyDirect('<?php echo addslashes($dir); ?>')">Copy Keeping Format</button>
内容的提问来源于stack exchange,提问作者KCode
相关产品推荐
相关产品推荐

