[英]Uploading file and simple previewing of the image display not working
我写了一个小的 function 选择图像并显示它的预览,但我无法弄清楚如何使它多次为不同的按钮工作。 请帮帮我:功能:
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files && this.files[0]) {
var img = document.getElementById('img1');
img.onload = () => {
URL.revokeObjectURL(img.src); // no longer needed, free memory
}
img.src = URL.createObjectURL(this.files[0]); // set src to blob url
}
});
});
问题是第二个按钮没有激活。 这是因为在这段代码中(在加载时执行):
document.querySelector('input[type="file"]').addEventListener('change', function() {
仅找到文件类型的输入元素的第一个实例。 这就是 document.querySelector 所做的。
要确保找到这种类型的每个按钮,以便您可以为其设置事件侦听器,请查看使用 document.querySelectorAll。 这将返回一个节点集合,而不仅仅是一个节点,因此您需要单步执行此集合,为每个元素设置一个事件侦听器。
请参阅https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.