[英]Can't run document.execCommand('copy); in Javascript
I'm trying to select and copy text from an html <textarea>
element, but using document.execCommand('copy');
我正在尝试从html <textarea>
元素中选择并复制文本,但是使用document.execCommand('copy');
displays an error stating that .execCommand('copy') is not a function.
显示错误,指出.execCommand('copy') is not a function.
. 。 I did also say myTextElement.select();
我也说过myTextElement.select();
before I ran the copy command. 在运行复制命令之前。 (And I am also using jQuery). (而且我也在使用jQuery)。
So as you know, I have a <textarea>
element with an id="txtMyTextElement"
tag. 如您所知,我有一个带有id="txtMyTextElement"
标签的<textarea>
元素。 I also have an anchor element which has a click event which runs a function like this: 我也有一个锚元素,它具有一个click事件,该事件运行如下函数:
$('#txtMyTextElement').select();
let result = document.execCommand('copy');
if (result === 'successful') {
alert('Text copied!');
}
else {
alert('Copy Failed!');
}
When I click my anchor element it gives me the error: .execCommand('copy') is not a function
. 当我单击我的锚元素时,它给了我错误: .execCommand('copy') is not a function
。 I might be missing something, but any help to fix this issue so I can copy text inside my <textarea>
element would be much appreciated. 我可能会缺少一些东西,但是要解决此问题的任何帮助,以便可以在<textarea>
元素内复制文本,将不胜感激。
While your code doesn't seem to be throwing a "is not a function" error, you do have another issue. 尽管您的代码似乎没有引发“不是函数”错误,但是您确实还有另一个问题。
Your issue seems to be with === "successful"
. 您的问题似乎与=== "successful"
。 This will never be true
. 这将永远是不true
。 Instead, document.execCommand('copy');
相反, document.execCommand('copy');
returns a boolean ( true
or false
) and so result
will either be equal to true
or false
: 返回一个布尔值( true
或false
),因此result
将等于true
或false
:
$("#btn").click(function() { $('#txtMyTextElement').select(); let result = document.execCommand('copy'); if(result) { // check if result == true alert('Text copied!'); } else { alert('Copy Failed!'); } })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id="txtMyTextElement" /> <button id="btn">Copy Text</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.