简体   繁体   中英

Event listeners are not working in IE and FF

this is part of my code (where event listeners are added to my images).

var overlay = this.overlay;
    var icon_holder = this.icon_hld;
    var docfrag = document.createDocumentFragment();
    var images = holder.querySelectorAll('img');
    var that = this;
    function video_play() {
        console.log(this);
        this.style.display = 'none';
        this.parentNode.querySelector('.JGalleryMedia').style.display = '';
        this.parentNode.querySelector('.JGalleryMedia').play();
        this.parentNode.querySelector('.JGalleryMedia').autoplay = true;
    }
    [].forEach.call(images, function (img) {
        img.addEventListener('click', JGallery.prototype.showMe.bind(that), false);
    }
}

this is working nicly in opera and chrome, but not working in IE and FF. I've seen caniuse.com, but I have not found anything I should not use in my code. If you want to see the working demo open zaervax.ir with chrome or opera and go to gallery and click on image thumbnails.

I am not sure but I think you cannot pass parameters like this in the eventListener.

You could try an anonymous function like this:

img.addEventListener('click', function(){
    JGallery.prototype.showMe.bind(that)
}, false);

Also if you want to pass this as a parameters you can use the ES6 Arrow functions, so that you will be able to access this in your showMe() function. It is done like that:

img.addEventListener('click', event => this.JGallery.prototype.showMe(event), false);

More infos about arrow functions

If this is not working, can you try to open your console and tell us if there is any error message?

ok IE problem was about forEach (without .call)(I had this in several lines above the mentioned lines). and FF (v47) seems to has problems with forEach. I have updated my FF (to v50)(problem solved without code changing). And I decided not to use forEach ever again, and I used while instead. like so...

 var i = 0;
 while(i < images.length){
    var img = images.item(i);
    img.addEventListener('click', JGallery.prototype.showMe.bind(that), false);
}

and now it's working nicely, you can check it out in zaervax.ir

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