输入addEventListener在更改时不触发 [英] Input addEventListener on change not firing

查看:136
本文介绍了输入addEventListener在更改时不触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只有一个输入即可上传图片.

I have a single input to upload a image.

html

<main>
    <input id="hs-p" type="file" accept="image/*" capture="camera">
</main>

<script type="text/javascript">
    let hsp = new HPS();
</script>

此输入更改时(当有人向其添加图像时),我想听.

I want to listen for when this input changes ( when someones adds an image to it).

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;

当某人添加图像时,应调用uploadImage回调.但是,此功能仅在页面加载时触发一次,而在将图像添加到输入或更改输入图像时永远不会触发.

When someone adds an image it should call the uploadImage callaback. However this function is only firing once when the page loads and never fires when i add a image to the input or change the input image.

我正在使用节点& webpack输出上述自定义库/sdk,然后将其导入到我的html中.

I am using node & webpack to output the above custom library/sdk which i then import into my html.

推荐答案

将您的活动更改为此:

this.imageInput.addEventListener("change", () => this.uploadImage());

或者对此:

this.imageInput.addEventListener("change", this.uploadImage.bind(this));

您正在做的是调用uploadImage并将其结果传递给侦听器.您要将引用传递给侦听器.

What you are doing is calling uploadImage and passing the result of that to the listener. You want to pass the reference to the listener.

这篇关于输入addEventListener在更改时不触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆