Kay*_*Kay 0 html javascript addeventlistener node.js webpack
我有一个输入来上传图像。
html
<main>
<input id="hs-p" type="file" accept="image/*" capture="camera">
</main>
<script type="text/javascript">
let hsp = new HPS();
</script>
Run Code Online (Sandbox Code Playgroud)
我想监听此输入何时更改(当有人向其中添加图像时)。
js
let imageInput = null;
class HSP {
constructor() {
this.imageInput = document.getElementById('hs-p');
if (this.imageInput) {
this.imageInput.addEventListener("change", this.uploadImage());
}
}
uploadImage() {
console.log("upload image", this.imageInput);
}
}
module.exports = HSP;
Run Code Online (Sandbox Code Playgroud)
当有人添加图像时,它应该调用 uploadImage 回调。但是,此功能仅在页面加载时触发一次,而在我向输入添加图像或更改输入图像时从不触发。
我正在使用 node & webpack 输出上面的自定义库/sdk,然后我将其导入到我的 html 中。
将您的活动更改为:
this.imageInput.addEventListener("change", () => this.uploadImage());
Run Code Online (Sandbox Code Playgroud)
或者到这个:
this.imageInput.addEventListener("change", this.uploadImage.bind(this));
Run Code Online (Sandbox Code Playgroud)
您正在做的是调用uploadImage并将结果传递给侦听器。您想将引用传递给侦听器。