我想为动态创建的控件使用Javascript复制到剪贴板功能。我的要求如下:
对于存在id的静态控件,它非常简单,但对于动态创建的控件,它不起作用。
function myFunction() {
/* Get the text field */
var copyText = document.getElementById("myInput");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
/* Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the text: " + copyText.value);
}
如何使复制到剪贴板工作的动态创建的控件?
发布于 2021-01-17 05:51:06
要为动态创建的控件实现复制到剪贴板,您可以使用以下javascript函数。
逻辑如下:
中的值
使用document.execCommand("copy"); ()和()等标准javascript方法从动态创建的输入复制
因此,每次它添加控制,一旦目的完成,就会删除它。它发生得如此之快,以至于没有人会注意到它。
下面是现成的方法:
function copyTextToClipboard(textToCopy) {
/* Append an input:type=text under the body*/
$("body").append("<div id=\"divCopyToClipboard\"><input type=\"text\" id=\"txtCopyToClipboard\" value=\"" + textToCopy + "\"></div>");
/* Set the value which user wish to copy to clipboard*/
$("#txtCopyToClipboard").val(textToCopy);
/* Get the control object*/
var copyText = document.getElementById("txtCopyToClipboard");
/* Select the text field */
copyText.select();
copyText.setSelectionRange(0, 99999); /* For mobile devices */
/*Copy the text inside the text field */
document.execCommand("copy");
/* Alert the copied text */
alert("Copied the variable: " + textToCopy);
/* Finally remove the dynamically created field*/
$("#divCopyToClipboard").remove();
}
希望你会发现它是有用的。
https://stackoverflow.com/questions/65757742
复制相似问题