未捕获的DOMException:未能执行'removeChild'在'节点'

Uncaught DOMException: Failed to execute 'removeChild' on 'Node'

本文关键字:removeChild 节点 DOMException 执行      更新时间:2023-09-26

未能在"Node"上执行"removeChild":要删除的节点为不是此节点的子节点。

当我执行下面的代码时,我得到了错误。有什么办法解决这个问题吗?

function clickLinks(links) {
  for(var item in links) {
      var anchor = document.createElement("a");
      anchor.target = "_blank";
      anchor.href   = links[item];
      document.body.appendChild(anchor);
      window.setTimeout(function() {
        anchor.dispatchEvent(new MouseEvent("click",{
              "bubbles"    : true,
              "cancelable" : true,
              "view"       : window
          }));

          window.setTimeout(function() {
              document.body.removeChild(anchor);
          }, 50);
      }, 50);
    }
   }

您需要为正在使用的锚变量创建一个闭包,以确保在for循环的下一次迭代中不会覆盖它。

function clickLinks(links) {
 for(var item in links) {
  var anchor = document.createElement("a");
  anchor.target = "_blank";
  anchor.href   = links[item];
  document.body.appendChild(anchor);
  (function iifeclosure(anchor){
  window.setTimeout(function() {
    anchor.dispatchEvent(new MouseEvent("click",{
          "bubbles"    : true,
          "cancelable" : true,
          "view"       : window
      }));

      window.setTimeout(function() {
          document.body.removeChild(anchor);
      }, 50);
  }, 50);
  })(anchor);
 }
}