【发布时间】:2018-06-06 21:10:50
【问题描述】:
我想在现有网页上添加一个按钮,用于将文本复制到 Windows 剪贴板。
网页和其中的 PHP 已经可以很好地创建和显示如下文本:
网页输出:
'Abby Normal' <abnormal@rockyhorror.com>, 'Brad Majors' <bm@rockyhorror.com>, 'Frank N. Furter' <franknfurter@rockyhorror.com>
所以现在我想添加一个 Javascript 函数和一个调用该函数以将该输出复制到 Windows 剪贴板的 html 按钮。
问题:按下按钮时没有复制任何内容。我究竟做错了什么?提前谢谢你。
<?PHP
session_start();
include('include/_initsess.php');
include('include/_setdb.php');
if(!isset($_SESSION['userlist'])) exit;
$users = $_SESSION['userlist'];
$emails = '';
$qry = "SELECT FIRST,LAST,EMAIL FROM users WHERE PKEY IN ($users)";
$result = mysql_query($qry);
$numrows = mysql_num_rows($result);
for ($m=0; $m<$numrows; $m++) {
$row = mysql_fetch_array($result);
list($fn,$ln,$em) = $row;
$emails .= ($m==0) ? "'".$fn." ".$ln."' <".$em.">" : (", '".$fn." ".$ln."' <".$em.">");
} // end for
?>
<html>
<head>
</head>
<body>
<span class=mono id="theList" value="<?php echo $emails; ?>">
<?PHP echo($emails); ?>
</span>
<script>
function copyToClipboardWithJavascript() {
/* Get the text field */
var copyText = document.getElementById("theList");
/* Select the text field */
copyText.select();
/* Copy the text inside the text field */
document.execCommand("copy");
}
</script>
<button onclick="copyToClipboardWithJavascript()">Click here</button>
</span>
</body>
</html>
我已经尝试了 Javascript 教程建议的方式:
var copyText = = document.getElementById("theList");
还有我自己在 Javascript 中使用 PHP 的变体:
var copyText = <?PHP echo($emails); ?>;
var copyText = `<?PHP echo($emails); ?>`;
var copyText = "<?PHP echo($emails); ?>";
var copyText = '<?PHP echo($emails); ?>';
但结果是不会导致任何错误,也不会将任何内容复制到剪贴板。
我知道该网页正在立即保存和使用,因为我还对按钮中的字母“单击此处”进行了细微的更改,刷新后可以看到不同之处。enter code here
***更新我使用的答案:****
<span class=mono id="theList">
<?PHP echo($emails); ?>
</span>
<button id="copyButton" onclick="myCopyFunction()">Copy email address list to clipboard.</button>
<script>
function myCopyFunction() {
var myText = document.createElement("textarea")
myText.value = document.getElementById("theList").innerHTML;
myText.value = myText.value.replace(/</g,"<");
myText.value = myText.value.replace(/>/g,">");
document.body.appendChild(myText)
myText.focus();
myText.select();
document.execCommand('copy');
document.body.removeChild(myText);
}
</script>
【问题讨论】:
-
您确定要公开这些电子邮件地址吗?
-
@GolezTrol 这些电子邮件地址代表虚构人物。参见洛基恐怖图片展。有效的关注虽然:)
-
@Flashdrive 值得关注,因为它是一个现有的域(实际上是 RHPS 粉丝俱乐部的),因此也可能是现有的电子邮件地址。如果这确实是那个网站的代码,那么这个问题也暴露了它使用的是旧版本的 PHP,不再有任何补丁,以及一段似乎容易受到 SQL 注入攻击的代码。我会做一个备份,只是为了确定。 ;-)
-
在那一行是 echo in span 它应该是 class="mono" 缺少引号
-
我刚刚编了邮件。
标签: javascript php html clipboard