简体   繁体   中英

Input addEventListener on change not firing

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;

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.

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

Change your event to this:

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

Or to this:

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

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.

change this.imageInput.addEventListener("change", this.uploadImage()); to this.imageInput.addEventListener("change", this.uploadImage); ( removed the () after this.uploadImage ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM