2016-10-25 10 views
3

'Node'で 'removeChild'を実行できませんでした:削除するノードは で、このノードの子ではありません。Uncaught DOMException: '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); 
    } 
    } 

答えて

2

あなたはそれがために、ループの次の反復で上書きされないことを確実にするために使用しているアンカー変数のクロージャを作成する必要があります。

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); 
} 
} 
関連する問題