未被捕获的DOMException:无法执行'节点'上的'removeChild' [英] Uncaught DOMException: Failed to execute 'removeChild' on 'Node'
问题描述
无法执行'Node'上的'removeChild':要移除的节点是
而不是此节点的子节点。
我在执行下面的代码时遇到错误。有什么方法可以解决这个问题吗?
pre $函数clickLinks链接{
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);
$ div $解析方案
你需要为你正在使用的anchor变量创建一个闭包,以确保它在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,{$ b $bubbles:true,
cancelable:true,
view:window
));
$ b window.setTimeout(function(){
document.body.removeChild(anchor);
},50);
},50);
})(anchor);
}
}
Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
I'm getting the error when I execute this code below. Is there any ways to solve this problem?
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);
}
}
You need to create a closure for the anchor variable you are using in order to ensure that it is not overwritten in the next iteration of the for loop.
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);
}
}
这篇关于未被捕获的DOMException:无法执行'节点'上的'removeChild'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!