Error: Failed to execut 'removeChild' on 'Node'

Error: Failed to execut 'removeChild' on 'Node'

我不熟悉 javascript 和一般的编程。我已经组装了我的第一个浏览器游戏,虽然一切正常,但我在控制台中不断收到这个讨厌的错误,显示 "NotFoundError: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node" 在我的悬停功能中。

function hover(myid) {
var id = myid;
var index = id[5];
document.getElementById(id).removeChild(GAME.mound[index]);
document.getElementById(id).appendChild(GAME.hover[index]);
GAME.sound[0].play();
}

GAME.mound和GAME.hover都是存储图片的数组。我想不通的是,我有一个几乎相同的功能来反转由悬停功能引起的图像切换,但它不会抛出错误。

function out(myid) {
var id = myid;
var index = id[5];
document.getElementById(id).removeChild(GAME.hover[index]);
document.getElementById(id).appendChild(GAME.mound[index]);
}

这是 HTML 中调用函数的一行:

<div id="drift0" class="snowdrift" onmouseover = "hover(this.id)" onmouseout = "out(this.id)" onclick = "popup(this.id)"></div>

非常感谢这方面的任何帮助。如果我没有提供回答问题所需的所有信息,请告诉我。

谢谢!

如果 hover 被调用两次而中间没有 out ,你就会遇到这个问题。该异常将导致回调退出——这不会导致问题,因为之前调用了 appendChild。我不记得确切的边缘情况,但我刚才确实看过这个。我建议您保留一个标志以确保它们仅作为切换执行。

什么都不做也不是致命的,虽然我不知道性能上的劣势是什么。最简单但不是最漂亮的解决方案是将其包装在 try catch 中:

try {
  document.getElementById(id).removeChild(GAME.mound[index]);
  document.getElementById(id).appendChild(GAME.hover[index]);
} catch(e) {}

最好查看您的代码并了解问题所在 and/or 找到阻止异常发生的解决方法。 GAME.sound[0].play();

看来你需要处理这个异常,那就处理吧。复制myid似乎没有任何意义,它是一个字符串,即使你修改它,原来的也没有改变。您应该将对元素的引用而不是 ID 传递给侦听器,因为它使用 getElementById 两次保存。

此外,正如 Deryck 所建议的,replaceChild 将一步完成更改:

function hover(myid) {
  var el = document.getElementById(myid);
  var index = myid[5];

  if (GAME.mound[index].parentNode === el) {
    // Replace mound image with hover image
    e.replaceChild(GAME.hover[index], GAME.mound[index]);
  }
  GAME.sound[0].play();
}

如果您将 this 传递给函数而不是 this.id,您可以这样做:

function hover(el) {
  var index = el.id[5];

  if (GAME.mound[index].parentNode === el) {
    e.replaceChild(GAME.hover[index], GAME.mound[index]);
  }
  GAME.sound[0].play();
}