文件输入的更改事件侦听器不起作用

Change Eventlistener on file input doesnt work

我目前正在开发一个网络应用程序,我有一个文件输入字段,用户可以在其中上传图像。我想确保真的只有图片通过 javascript 上传。无论如何我无法让事件监听器工作......你可以在下面找到相关的代码片段:

"use strict";
document.addEventListener("DOMContentLoaded", init);

function init() {
    document.getElementById("reset").addEventListener("click", setBack);
    document.getElementById("anlegen").addEventListener("click", anlegen);
    document.getElementById("file").addEventListener("change", test);
}

//Check Image Funktion von https://dev.to/faddalibrahim/filtering-and-validating-file-uploads-with-javascript-327p
function test {
    alert("test");
}
<div class="col-4">  
  <label for="file">Bild</label>
  <input type="file" name="file" id="file" accept="image/*" required>
</div>

您在 test 的函数声明中忘记了 (),并且有几个 document.getElementById 用于不存在的 html 元素不存在函数。

见下文,效果非常好。

"use strict";
document.addEventListener("DOMContentLoaded", init);

function init() {
    document.getElementById("file").addEventListener("change", test);
}

//Check Image Funktion von https://dev.to/faddalibrahim/filtering-and-validating-file-uploads-with-javascript-327p
function test() {
    alert("test");
}
<div class="col-4">  
  <label for="file">Bild</label>
  <input type="file" name="file" id="file" accept="image/*" required>
</div>