javascript - 当我尝试在单击时添加图像时,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>
解决方案
好的,用这个。首先,有一个输入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>
推荐阅读
- java - Spring 5 Webclient 在 doAfterSuccessOrError 中抛出异常
- algorithm - 带摩擦的运动算法
- excel - Excel,如何删除excel表格中的某些范围值,如果可能的话,从表格列表中删除它们
- c# - 为什么 Pcap.net ReceivePacket 有 1000 毫秒的延迟?
- python - 如何将系统音频抓取到 python?
- apache-poi - Apache POI 中的 Excel 工作表名称(没有“用户”模型)
- typescript - 打字稿类型 RequireSome
从属性中删除 undefined AND null - cocoa - keyDown(with:) 不在自定义 ViewController 或 View 上调用,仅在 WindowController 上调用
- angularjs - 日期选择器的 Angular 指令自动完成
- javascript - 如何在画布中重绘一个矩形?