NoNameZ
NoNameZ

Reputation: 795

jQuery each callback

How to use callbacks on jQuery each function?

I am trying something like:

$.each(images, function(key, value) { 
    new_images+= '<li><a href="'+value+'"><img src="'+value+'" alt="'+[key]+'" /></a></li>';
}, function (){
    $('#Gallery').remove();
    $('body').append('<ul class="gallery">'+new_images+'</ul>');
});

Upvotes: 17

Views: 45069

Answers (5)

FishWave
FishWave

Reputation: 308

I have now a solution for an .each-callback!

I had to do an ajax-request for each element in an array. So I made a div-container with all the div-elements for each element. Each time a load was made, the div-element changed to green and .slideUp, after .remove. And each time i asked if the div-container is empty. If yes, I know, all elements are fully loades (because removed).

Here a part of my code:

<script>
$(document).ready( function() {
    $.each(myChannels, function(index, value) {
        $("#tag_"+value).load('getxmls/ajaxrenewchannel/channel:'+value, function() {
            $("#tag_"+value).removeClass('alert-info').addClass('alert-success');
            $("#tag_"+value).slideUp('600', function () {
                $("#tag_"+value).remove();
                if( $('#loadcontainer').is(':empty') ) {
                    window.location = 'feeds/';
                }

                });

        });
    });
});
</script>

Hope this helps somebody out there...

Upvotes: 1

Damian SIlvera
Damian SIlvera

Reputation: 866

$.each(); is a synchronous function. That means you don't need a callback function inside because any code you write after $.each(); will run affter $.each(); ends.

Upvotes: 49

Shyju
Shyju

Reputation: 218732

Not sure about the callback you meant. I guess this is what you are looking for

$('#Gallery').remove();
var selectItems='<ul class="gallery">';
$.each(images, function(key, value) { 
    selectItems+= '<li><a href="'+value+'">
                              <img src="'+value+'" alt="'+[key]+'" /></a></li>';    
});   
selectItems+= '</ul>';
$('body').append(selectItems);

Upvotes: 0

h2ooooooo
h2ooooooo

Reputation: 39532

What's wrong with this code? You don't need a callback for $.each.

$.each(images, function(key, value) { 
    new_images+= '<li><a href="'+value+'"><img src="'+value+'" alt="'+[key]+'" /></a></li>';
});

$('#Gallery').remove();
$('body').append('<ul class="gallery">'+new_images+'</ul>');

Upvotes: 28

Arsen Mkrtchyan
Arsen Mkrtchyan

Reputation: 50712

Do you mean this?

$.each(images, function(key, value) { 
    new_images+= '<li><a href="'+value+'"><img src="'+value+'" alt="'+[key]+'" /></a></li>';
});
function myMethod(){
    $('#Gallery').remove();
    $('body').append('<ul class="gallery">'+new_images+'</ul>');
};
myMethod();

Upvotes: 1

Related Questions