简体   繁体   中英

jQuery trigger click in loop stops after the first

I'm trying to do this, but the loop ends after the first trigger. Any ideas to help me out?

$(document).on('click', '#configurator .myalbumimgs .autofill', function(e) {

    e.preventDefault();

    var nb_of_images = $('#grid div.configimg').length;

    for (i = 0; i < nb_of_images; i++) {

        alert(i);

        $('.imgpicker .photo .add').eq(i).trigger('click');
    }

}); 

Edit 1: Everything works fine if I remove $('.imgpicker .photo .add').eq(i).trigger('click'); and just let the loop run.

If I put a number in, like eq(3) selects the right one, but only that one. Then it stops as before.

No errors in console :S

Edit 2: Found out the correct solution, my mistake with .eq on the wrong element. Thanks for all suggestions! Correct code:

$(document).on('click', '#configurator .myalbumimgs .autofill', function(e) {

    e.preventDefault();

    if ($(this).not('.done')) {

        var multiselector_nbimages = $('#grid').attr('data-nbimages');

        var nb_images_selected = parseInt($('#grid div.configimg').not('.temp').length);
        var max_nb_images = parseInt(multiselector_nbimages);

        if (nb_images_selected < max_nb_images) {

            var album_images = $(this).parent().parent().children('.imgpicker').children('.photo');
            var nb_of_grid_images = $('#grid div.configimg.temp').length;

            for (i = 0; i < nb_of_grid_images; i++) {

                album_images.eq(i).children('.add').not('.selected').trigger('click');;
            }

            $(this).addClass('done');

        } else {

            alert(lang_valid_max_nb_of_photos);
        }

    }

});

jquery has built in each method .

$('#configurator .albumbtn.autofill').on('click', function(e) {

e.preventDefault();

//Iterate through every configimg
$('#grid div.configimg').each(function(el) {
// $(this) is current element in the list
   if($(this).hasClass('someclass')) { $(this).trigger('click') }
})

});

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