javascript - 将 this 传递给 setTimeout 函数会导致 Uncaught TypeError: this.empty is not a function
问题描述
我正在尝试在我的应用程序中实现复制到剪贴板按钮,但我无法使用该setTimeout
方法更新按钮文本。当我单击按钮时,我在控制台中收到以下错误
jquery-1.12.4.js:6375 Uncaught TypeError: this.empty is not a function
at HTMLButtonElement.<anonymous> (jquery-1.12.4.js:6375)
at access (jquery-1.12.4.js:4399)
at HTMLButtonElement.html (jquery-1.12.4.js:6338)
at access (jquery-1.12.4.js:4416)
at jQuery.fn.init.html (jquery-1.12.4.js:6338)
at scripts.js:126
到目前为止,这是我的代码。
我的代码:
$('button.copy-to-clipboard').on('click', function() {
element = $(this).prev('.copy-text')[0];
var selection = window.getSelection();
var range = document.createRange();
var default_html = $(this).html;
var that = this;
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
try {
var successful = document.execCommand('copy');
if (successful) {
$(that).addClass("copied");
$(that).html("Copied");
setTimeout(function() {
$(that).removeClass("copied");
$(that).html(default_html);
}, 2000);
} else {
$(that).addClass("copy-error");
$(that).html("Unable to copy");
setTimeout(function() {
$(that).removeClass("copy-error");
$(that).html(default_html);
}, 2000);
}
} catch (err) {
$(this).html(err);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="copy-container"><span class="copy-text">6145555555</span><button class="copy-to-clipboard">Copy</button></span>
当您回答时,请考虑到我不是前端开发人员。我对 JavaScript 和 jQuery 的细微差别完全陌生!
解决方案
推荐阅读
- mongodb - 在 ubuntu 上安装最小的 mongo 包
- sql - 如何在更新时强制转换 varchar?
- c# - 如何将 Claimtypes.NameIdentifier 作为 UserId 值设置为新用户的其他数据库表中的多行
- typescript - 在 Typescript 中通过名称获取类方法的返回类型
- amazon-web-services - “max_user_history_length”:“200”,默认 aws 个性化 - 个性化排名配方超参数是什么意思?
- amazon-web-services - ECS“为服务选择一个有效的部署组。” 代码部署
- java - 为什么 for 循环不适用于 array.size()?
- javascript - for、while 和 do while 循环之间到底有什么区别?在哪种情况下我应该使用每种情况?
- flutter - 未处理的异常:FormatException:不是有效的链接本地地址,但包含 %
- node.js - apt 命令无法找到 npm 和节点包