首页 > 解决方案 > 当我尝试在单击时添加图像时,Javascript appendChild() 不起作用

问题描述

我正在尝试在按钮单击时将图像添加到页面,但经过大量测试后,它仍然无法正常工作。这是我的代码:

const button = document.querySelector('button');
button.addEvenListener('click', event => {

var othermonke = document.createElement("img");
othermonke.src = ""../../Downloads/monke.jpg" width="200" height="200" alt=""";
othermonke.appendChild(othermonke)
})
<button type="button">Click me</button>

标签: javascript

解决方案


好的,用这个。首先,有一个输入addEventListener(您可以通过在 Chrome 和大多数主要浏览器中执行 Ctrl + Shift + J 来检查此类错误)。然后,您需要将图像附加到 DOM 中已经存在的元素中。在这里,作为一个例子,我使用了按钮的父元素,无论它可能是什么:

const button = document.querySelector('button');
button.addEventListener('click', event => {

   const othermonke = document.createElement("img");
   othermonke.src = "https://via.placeholder.com/200";
   othermonke.width = "200"; // Better practice is to use setAttribute here
   othermonke.height = "200";
   othermonke.alt = "alttext";

   button.parentElement.appendChild(othermonke);
});
<button>btn</button>


推荐阅读