我写了一个小函数,可以拾取图像并显示其预览,但我不知道如何让它对不同的按钮进行多次类似的操作。请帮帮我!功能:
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() {
只找到类型为file的输入元素的第一个实例。document.querySelector就是这样做的。
要确保找到此类型的每个按钮,以便为其设置事件侦听器,请查看使用document.querySelectorAll。这将返回一个节点集合,而不仅仅是一个节点,因此您需要遍历此集合,为每个元素设置一个事件侦听器。
请参阅https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll