我正在制作一款打地鼠的游戏,要想在洞里制造一只鼹鼠,我需要一张图片.我找到了该图像,并使用JavaScript插入了该图像.在下面的代码中,我在另一个文件中执行了该操作,在该文件中我正在try 查看哪一种方法可以正常工作:

<div class="hole" id="h1"></div>
<script>
  let mole = `<img src="mole.jpg" height="70px" width="70px" class="mole">`;
  let moleNode = document.querySelector('.mole');
  document.querySelector('#h1').innerHTML = mole;
  document.querySelector('#h1').removeChild(moleNode); // Error: moleNode is not of type node.
  // I also tried:
  mole.parentNode.removeChild(moleNode); // Same thing as above. Also I thought it wouldn't work because there were 36 holes and I don't actually know how to do it then.
</script>

推荐答案

问题是您试图在将moleNode添加到DOM之前将其删除.你需要调换这两条线路才能把它修好.此外,在代码中还有一个建议是,将id命名为具有标准HTML元素(在您的示例中为h1)并不是一个好主意,所以我更改了它.

let mole = `<img src="mole.jpg" height="70px" width="70px" class="mole">`;
document.querySelector('#specific-id').innerHTML = mole; // Swapped with below

let moleNode = document.querySelector('.mole'); // Swapped with above

// Remove the moleNode when needed
moleNode.parentNode.removeChild(moleNode);
// or document.querySelector('#specific-id').removeChild(moleNode);
<div class="hole" id="specific-id"></div>

Javascript相关问答推荐

如何在NightWatch.js测试中允许浏览器权限?

Cookie中未保存会话数据

colored颜色 检测JS,平均图像 colored颜色 检测JS

如何将Cookie从服务器发送到用户浏览器

当输入字段无效时,我的应用程序不会返回错误

有条件重定向到移动子域

确保函数签名中的类型安全:匹配值

在画布中调整边上反弹框的大小失败

Reaction-SWR-无更新组件

与svg相反;S getPointAtLength(D)-我想要getLengthAtPoint(x,y)

无法读取未定义的属性(正在读取合并)-react RTK

有没有办法更改Chart.js 3.x.x中主要刻度的字体?

如何使用[ModelJSON,ArrayBuffer]调用tf.loadGraphModelSync

如何在下一个js中更改每个标记APEXCHARTS图表的 colored颜色

如果我的列有条件,我如何呈现图标?

JavaScript:多个图像错误处理程序

在Press Reaction本机和EXPO av上播放单个文件

使用onClick单击子元素时,使用交点观察器的关键帧动画意外运行

使用JAVASCRIPT-使用If和Else If多次判断条件-使用JAVASRIPT对象及其属性

如何让noWrap在嵌套在Alert/AlertTitle组件中的排版组件中工作?