简体   繁体   中英

JavaScript not triggering events when dynamically loaded

I'm using the Swiper.js library and I have an issue getting the 'slideChange' event to trigger when dynamically loading elements through JavaScript.

Here is where my swipers both horizontal and vertical are initialised:

 var swiper = { initialize: function() { swiperH = new Swiper('.swiper-container-h', { slidesPerView: 1, preloadImages: false, updateOnImagesReady: true, lazy: true, }).on('slideChange', function () { console.log('Swiped Horizonally'); }); swiperV = new Swiper('.swiper-container-v', { direction: 'vertical', slidesPerView: 1, preloadImages: false, updateOnImagesReady: true, lazy: true, effect: 'fade', loop: true, fadeEffect: { crossFade: true }, pagination: { el: '.swiper-pagination-v', clickable: true, }, }).on('slideChange', function () { console.log('Swiped Vertically'); }); } };

The reason why the horizontal's 'slideChange' triggers is because its already in the html file:

 <!-- Swiper --> <div class="dash-container"> <div class="swiper-container swiper-container-h"> <div class="swiper-wrapper" id="swipeData"> </div> </div> </div>

Now, the vertical slides are loading through JavaScript and that's where the vertical's 'slideChange' doesn't trigger.

 function loadDresses(selectedDresses) { return new Promise((resolve, reject) => { $('#swipeData').html(''); for (var i = 0; i < selectedDresses.length; i++) { var vScroll = '<div class="swiper-slide"><div class="swiper-container swiper-container-v"><div class="swiper-wrapper" style="height: 100%;">'; for (var j = 0; j < selectedDresses[i].images.length; j++) { vScroll += '<div class="swiper-slide"><img src="' + selectedDresses[i].images[j] + '"/></div>'; } vScroll += '<div class="swiper-slide" style="display:table;height:100%;width:100%;">'; vScroll += '</div></div></div><div class="swiper-pagination swiper-pagination-v">'; $('#swipeData').append(vScroll).trigger('create'); } resolve(true); }); }

The error occurs at this snippet:

    .on('slideChange', function () {
        console.log('Swiped Vertically');
    });

有了这个错误

Any ideas? Thanks!

Edit:

I have tried the following to stop it from initialising too early, but still no luck:

          loadDresses(dresses).then(function(result) {
            var t = setInterval(() => {
                swiper.initialize();
                clearInterval(t);
            }, 5000);
        });

And doesn't that help?

var swiper = {
    initialize : function() {
        swiperH = new Swiper('.swiper-container-h', {
            slidesPerView: 1,
            preloadImages: false,
            updateOnImagesReady: true,
            lazy: true,
        })
        .on('slideChange', function () {
            console.log('Swiped Horizonally');
        });

        swiperV = new Swiper('.swiper-container-v', {
            direction: 'vertical',
            slidesPerView: 1,
            preloadImages: false,
            updateOnImagesReady: true,
            lazy: true,
            effect: 'fade',
            loop: true,
            fadeEffect: {
                crossFade: true
            },
            pagination: {
                el: '.swiper-pagination-v',
                clickable: true,
            },
            on: {
                slideChange: function() {
                    console.log('Swiped Vertically');
                }
            }
        });
    }
};

You have some options here:

To keep the flow of your application, you can destroy the slider and reinitialize it.

swiperH.destroy()

then

loadDresses();
swiper.initialize();

OR

you can just mySwiper.update() every time you change your slide manually

The problem is that an element with class swiper-pagination-v is not found during initialization.

You can make condition for class swiper-pagination-v exists.

var swiper = {
    initialize : function() {
        swiperH = new Swiper('.swiper-container-h', {
            slidesPerView: 1,
            preloadImages: false,
            updateOnImagesReady: true,
            lazy: true,
        })
            .on('slideChange', function () {
                console.log('Swiped Horizonally');
            });

        if ($('.swiper-container-v').length > 0) {
            swiperV = new Swiper('.swiper-container-v', {
                direction: 'vertical',
                slidesPerView: 1,
                preloadImages: false,
                updateOnImagesReady: true,
                lazy: true,
                effect: 'fade',
                loop: true,
                fadeEffect: {
                    crossFade: true
                },
                pagination: {
                    el: '.swiper-pagination-v',
                    clickable: true,
                },
            })
                .on('slideChange', function () {
                    console.log('Swiped Vertically');
                });
        }
    }
};

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