首页 > 解决方案 > 将 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 的细微差别完全陌生!

标签: javascriptjquerythissettimeout

解决方案


推荐阅读