首页 > 解决方案 > 如何删除最后执行的命令html + javascript?

问题描述

我有两个页面,第 1 页和第 2 页。对于第 2 页,我的代码是这样的:

 $("input[value]").each(function(r) {
          if (r == 6) {
            $(this).focus();

            document.execCommand("insertText", false, request.data.email);
            setTimeout(() => {
              document.execCommand("delete", false, null);
              console.log('deleted')
            }, 3000);
          }
        });

我已成功将文本复制到输入,但如果我移动到第 1 页,然后再次回到第 2 页,然后调用该函数,我仍然看到我之前复制的原始数据仍然存在。

我的问题:如何删除最后一个命令document.execCommand("insertText", false, request.data.email);?我尝试过类似这样document.execCommand("delete", false, null);的命令:,但它不起作用。

标签: javascripthtmldom

解决方案


使用undo commanddelete将删除当前选择,而不是最后一个命令:

$("input[value]").each(function(r) {
  if (r == 6) {
    $(this).focus();
    document.execCommand("insertText", false, request.data.email);
    setTimeout(() => {
      document.execCommand("undo", false, null);
      console.log('undone')
    }, 3000);
  }
});

推荐阅读